Computer >> Máy Tính >  >> Lập trình >> C#

Phương thức DateTime.AddMonths () trong C #

Phương thức DateTime.AddMonths () trong C # được sử dụng để thêm số tháng được chỉ định vào giá trị của trường hợp này.

Cú pháp

Sau đây là cú pháp -

public DateTime AddMonths (int val);

Ở trên, Val là số tháng. Nếu bạn muốn trừ các tháng, hãy đặt nó là số âm.

Ví dụ

Bây giờ chúng ta hãy xem một ví dụ để triển khai phương thức DateTime.AddMonths () -

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);
   }
}

Đầu ra

Điều này sẽ tạo ra kết quả sau -

Initial DateTime = 15 May 2019, 05:15:25
New DateTime (After adding months) = 15 October 2019, 05:15:25

Ví dụ

Bây giờ chúng ta hãy xem một ví dụ khác để triển khai phương thức DateTime.AddMonths () -

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);
   }
}

Đầu ra

Điều này sẽ tạo ra kết quả sau -

Initial DateTime = 20 August 2019, 03:30:50
New DateTime (After subtracting months) = 20 June 2019, 03:30:50