DateTimeOffset.AddYears() Method in C#


The DateTimeOffset.AddYears() method in C# is used to add a specified number of years to the value of this instance.

Syntax

Following is the syntax −

public DateTimeOffset AddYears (int val);

Above, the Val parameter is the years to be added to the offset. To subtract, you need to set negative values.

Example

Let us now see an example to implement the DateTimeOffset.AddYears() method −

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);
   }
}

Output

This will produce the following output −

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

Example

Let us now see another example to implement the DateTimeOffset.AddYears() method −

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);
   }
}

Output

This will produce the following output −

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
raja
Published on 06-Nov-2019 06:01:52
Advertisements