Phương thức DateTime.AddMonths() trong C# được dùng để thêm số tháng được chỉ định vào giá trị của thể hiện này.
Cú pháp
Cú pháp như sau:
public DateTime AddMonths(int val);
Tham số val là số tháng. Để trừ tháng, sử dụng giá trị âm.
Ví dụ 1 - Thêm 5 tháng
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("\nNew DateTime (After adding months) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
}
}
Kết quả
Initial DateTime = 15 May 2019, 05:15:25 New DateTime (After adding months) = 15 October 2019, 05:15:25
Ví dụ 2 - Trừ 2 tháng
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("\nNew DateTime (After subtracting months) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
}
}
Kết quả
Initial DateTime = 20 August 2019, 03:30:50 New DateTime (After subtracting months) = 20 June 2019, 03:30:50