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
Selected Reading
DateTime.AddMonths() Method in C#
The DateTime.AddMonths() method in C# is used to add the specified number of months to the value of this instance.
Syntax
Following is the syntax −
public DateTime AddMonths (int val);
Above, Val is the number of months. If you want to subtract months, then set it as negative.
Example
Let us now see an example to implement the DateTime.AddMonths() method −
using System;
public class Demo {
public static void Main(){
DateTime d1 = new DateTime(2019, 05, 15, 5, 15, 25);
DateTime d2 = d1.AddMonths(5);
System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
System.Console.WriteLine("\nNew DateTime (After adding months) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
}
}
Output
This will produce the following output −
Initial DateTime = 15 May 2019, 05:15:25 New DateTime (After adding months) = 15 October 2019, 05:15:25
Example
Let us now see another example to implement the DateTime.AddMonths() method −
using System;
public class Demo {
public static void Main(){
DateTime d1 = new DateTime(2019, 08, 20, 3, 30, 50);
DateTime d2 = d1.AddMonths(-2);
System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
System.Console.WriteLine("\nNew DateTime (After subtracting months) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
}
}
Output
This will produce the following output −
Initial DateTime = 20 August 2019, 03:30:50 New DateTime (After subtracting months) = 20 June 2019, 03:30:50
Advertisements
