Calendar.AddYears Method
Adds a specified number of years to the value of the specified date and time.
Syntax
public abstract int AddYears(
int years
);
Parameters:
years
System.Int32
The number of years to add. The value can be positive or negative.
Return Value:
System.Int32
The date and time that result from adding the specified number of years to the current date and time.
Description
The AddYears
method calculates a new date by adding a specified number of years to the current date. This method is abstract, meaning it must be implemented by derived classes of Calendar
, such as GregorianCalendar
or HebrewCalendar
, each providing its own logic for year addition based on its specific calendar system.
When adding years, the method considers leap years and the specific rules of the calendar. For example, adding one year to February 29th in a leap year might result in February 28th of the following year if that year is not a leap year.
Remarks
Note: This method is part of the Calendar
abstract class. You will typically interact with this method through an instance of a concrete Calendar
implementation (e.g., new GregorianCalendar().AddYears(5)
).
Examples
The following C# example demonstrates how to use the AddYears
method with a GregorianCalendar
instance.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
// Get the current date and time
DateTime january272023 = new DateTime(2023, 1, 27);
Console.WriteLine("Original date: {0}", january272023.ToString("yyyy-MM-dd"));
// Use GregorianCalendar to add years
Calendar gregorianCalendar = new GregorianCalendar();
// Add 5 years
DateTime datePlus5Years = gregorianCalendar.AddYears(january272023.Year, january272023.Month, january272023.Day, 5);
Console.WriteLine("Date after adding 5 years: {0}", datePlus5Years.ToString("yyyy-MM-dd"));
// Add -2 years
DateTime dateMinus2Years = gregorianCalendar.AddYears(january272023.Year, january272023.Month, january272023.Day, -2);
Console.WriteLine("Date after subtracting 2 years: {0}", dateMinus2Years.ToString("yyyy-MM-dd"));
// Example with a leap year date
DateTime february292020 = new DateTime(2020, 2, 29);
Console.WriteLine("Original leap date: {0}", february292020.ToString("yyyy-MM-dd"));
DateTime leapDatePlus1Year = gregorianCalendar.AddYears(february292020.Year, february292020.Month, february292020.Day, 1);
Console.WriteLine("Leap date after adding 1 year: {0}", leapDatePlus1Year.ToString("yyyy-MM-dd")); // Should be 2021-02-28
DateTime leapDatePlus4Years = gregorianCalendar.AddYears(february292020.Year, february292020.Month, february292020.Day, 4);
Console.WriteLine("Leap date after adding 4 years: {0}", leapDatePlus4Years.ToString("yyyy-MM-dd")); // Should be 2024-02-29
}
}
Requirements
Namespace: System.Globalization
Assembly: mscorlib.dll (in mscorlib.dll)