C# DateTime AddYears

Description

DateTime AddYears returns a new DateTime that adds the specified number of years to the value of this instance.

Syntax

DateTime.AddYears has the following syntax.


public DateTime AddYears(
  int value
)

Parameters

DateTime.AddYears has the following parameters.

  • value - A number of years. The value parameter can be negative or positive.

Returns

DateTime.AddYears method returns An object whose value is the sum of the date and time represented by this instance and the number of years represented by value.

Example

The following example illustrates using the AddYears method with a DateTime value that represents a leap year day.

It displays the date for the fifteen years prior to and the fifteen years that follow February 29, 2000.


using System;//from ww  w.  j ava  2 s  .c o  m

public class Example
{
   public static void Main()
   {
      DateTime baseDate = new DateTime(2000, 2, 29);
      Console.WriteLine("    Base Date:        {0:d}\n", baseDate);

      for (int ctr = -1; ctr >= -15; ctr--){
         Console.WriteLine("{0,2} year(s) ago:        {1:d}", 
                           Math.Abs(ctr), baseDate.AddYears(ctr));
      }
      for (int ctr = 1; ctr <= 15; ctr++){
         Console.WriteLine("{0,2} year(s) from now:   {1:d}", 
                           ctr, baseDate.AddYears(ctr));
      }
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version