DateTime.AddMonths() Method in C#
Last Updated :
18 Jan, 2019
This method is used to return a new DateTime that adds the specified number of months to the value of this instance.
Syntax:
public DateTime AddMonths (int months);
Here, months is the number of months. The months parameter can be negative or positive.
Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and months.
Exception: This method will throw ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue or
months is less than -120, 000 or greater than 120, 000.
Below programs illustrate the use of the above-discussed method:
Example 1:
using System;
class GFG {
public static void Main()
{
DateTime d1 = new DateTime(2018, 4, 17);
for ( int i = 0; i <= 10; i++)
{
Console.WriteLine(d1.AddMonths(i).ToString( "d" ));
}
Console.WriteLine( "In Leap Years:" );
DateTime d2 = new DateTime(2016, 03, 31);
int m = 1;
Console.WriteLine(d2.AddMonths(m).ToString( "d" ));
}
}
|
Output:
04/17/2018
05/17/2018
06/17/2018
07/17/2018
08/17/2018
09/17/2018
10/17/2018
11/17/2018
12/17/2018
01/17/2019
02/17/2019
In Leap Years:
04/30/2016
Example 2:
using System;
class GFG {
public static void Main()
{
DateTime d1 = DateTime.MaxValue;
int m = 12005;
Console.WriteLine(d1.AddMonths(m).ToString( "d" ));
}
}
|
Runtime Error:
Unhandled Exception:
System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime.
Parameter name: months
Note:
- This method does not change the value of this DateTime object. Instead, it returns a new DateTime object whose value is the result of this operation.
- This calculates the resulting month and year, taking into account leap years and the number of days in a month, then adjusts the day part of the resulting DateTime object.
- The time-of-day part of the resulting DateTime object remains the same as this instance.
Reference:
Share your thoughts in the comments
Please Login to comment...