Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
DateTime.AddMonths() Method in C#
The DateTime.AddMonths() method in C# is used to add the specified number of months to the value of a DateTime instance. This method returns a new DateTime object representing the date after adding the specified months, while the original DateTime remains unchanged.
Syntax
Following is the syntax for the DateTime.AddMonths() method −
public DateTime AddMonths(int months);
Parameters
months − An integer representing the number of months to add. Use positive values to add months and negative values to subtract months. The value can range from -120,000 to 120,000.
Return Value
Returns a new DateTime object whose value is the sum of the date and time represented by this instance and the number of months represented by the months parameter.
Using AddMonths() to Add Months
Example
using System;
public class Demo {
public static void Main() {
DateTime d1 = new DateTime(2019, 05, 15, 5, 15, 25);
DateTime d2 = d1.AddMonths(5);
Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss}", d1);
Console.WriteLine("New DateTime (After adding months) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss}", d2);
}
}
The output of the above code is −
Initial DateTime = 15 May 2019, 05:15:25 New DateTime (After adding months) = 15 October 2019, 05:15:25
Using AddMonths() to Subtract Months
Example
using System;
public class Demo {
public static void Main() {
DateTime d1 = new DateTime(2019, 08, 20, 3, 30, 50);
DateTime d2 = d1.AddMonths(-2);
Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss}", d1);
Console.WriteLine("New DateTime (After subtracting months) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss}", d2);
}
}
The output of the above code is −
Initial DateTime = 20 August 2019, 03:30:50 New DateTime (After subtracting months) = 20 June 2019, 03:30:50
Handling End-of-Month Scenarios
When adding months to a date, if the resulting day doesn't exist in the target month, the method automatically adjusts to the last day of that month −
Example
using System;
public class Demo {
public static void Main() {
DateTime d1 = new DateTime(2019, 01, 31);
DateTime d2 = d1.AddMonths(1);
DateTime d3 = d1.AddMonths(2);
Console.WriteLine("Original Date: {0:dd MMMM yyyy}", d1);
Console.WriteLine("Add 1 month: {0:dd MMMM yyyy}", d2);
Console.WriteLine("Add 2 months: {0:dd MMMM yyyy}", d3);
}
}
The output of the above code is −
Original Date: 31 January 2019 Add 1 month: 28 February 2019 Add 2 months: 31 March 2019
Conclusion
The DateTime.AddMonths() method provides a reliable way to add or subtract months from a DateTime instance. It automatically handles edge cases like end-of-month scenarios and returns a new DateTime object while preserving the original date value.
