C#中的DateTimeOffset.AddYears()方法
C#中的DateTimeOffset.AddYears()方法用于将指定的年份添加到此实例的值。
语法
以下是语法-
public DateTimeOffset AddYears (int val);
上面的Val参数是要添加到偏移量的年份。要减去,您需要设置负值。
示例
现在让我们看一个实现DateTimeOffset.AddYears()方法的示例-
using System; public class Demo { public static void Main() { DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 06, 09, 8, 20, 10, new TimeSpan(-5, 0, 0)); Console.WriteLine("DateTimeOffset (before adding years) = {0}", dateTimeOffset); DateTimeOffset res = dateTimeOffset.AddYears(5); Console.WriteLine("DateTimeOffset (after adding years) = {0}", res); } }
输出结果
这将产生以下输出-
DateTimeOffset (before adding years) = 6/9/2019 8:20:10 AM -05:00 DateTimeOffset (after adding years) = 6/9/2024 8:20:10 AM -05:00
示例
现在让我们来看另一个实现DateTimeOffset.AddYears()方法的示例-
using System; public class Demo { public static void Main() { DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 06, 09, 8, 20, 10, new TimeSpan(-5, 0, 0)); Console.WriteLine("DateTimeOffset (before subtracting years) = {0}", dateTimeOffset); DateTimeOffset res = dateTimeOffset.AddYears(-3); Console.WriteLine("DateTimeOffset (after subtracting years) = {0}", res); } }
输出结果
这将产生以下输出-
DateTimeOffset (before adding years) = 6/9/2019 8:20:10 AM -05:00 DateTimeOffset (after adding years) = 6/9/2024 8:20:10 AM -05:00