DateTime.AddMonths() Method in C#
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:
// C# program to demonstrate the // DateTime.AddMonths(Int32) Method using System; class GFG { // Main Method public static void Main() { // Creating a DateTime object DateTime d1 = new DateTime(2018, 4, 17); for ( int i = 0; i <= 10; i++) { // using the method Console.WriteLine(d1.AddMonths(i).ToString( "d" )); } Console.WriteLine( "In Leap Years:" ); // Creating a DateTime object // by taking a leap year // It is 31st March 2016 DateTime d2 = new DateTime(2016, 03, 31); // taking a month value int m = 1; // using the method // Result will be 30 April 2016 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:
// C# program to demonstrate the // DateTime.AddMonths(Int32) Method using System; class GFG { // Main Method public static void Main() { // Creating a DateTime object // taking MaxValue DateTime d1 = DateTime.MaxValue; // taking a month MaxValue int m = 12005; // using the method will // give an runtime error // as months parameter is // greater than 12000 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:
- https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addmonths?view=netframework-4.7.2
Contact Us