DateTime.AddYears() Method in C#


The DateTime.AddYears() method in C# is used to add the specified number of years to the value of this instance. It returns new DateTime.

Syntax

Following is the syntax −

public DateTime AddYears (int yrs);

Above, yrs are the years to be added. If you want to subtract years, then use a negative value.

Example

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

using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 11, 20, 6, 20, 40);
      DateTime d2 = d1.AddYears(5);
      Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
      Console.WriteLine("New DateTime (added years) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
   }
}

Output

This will produce the following output −

Initial DateTime = 20 November 2019, 06:20:40
New DateTime = 20 November 2024, 06:20:40

Example

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

using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 11, 20, 6, 20, 40);
      DateTime d2 = d1.AddYears(-2);
      Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
      Console.WriteLine("New DateTime (subtracting years) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
   }
}

Output

This will produce the following output −

Initial DateTime = 20 November 2019, 06:20:40
New DateTime (subtracting years) = 20 November 2017, 06:20:40

Updated on: 06-Nov-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements