Phương thức DateTimeOffset.AddMonths() trong C# được sử dụng để thêm một số tháng được chỉ định vào giá trị của thể hiện này.
Cú pháp
Dưới đây là cú pháp:
public DateTimeOffset AddMonths (int val);
Trong đó, val là số tháng cần thêm. Để trừ tháng, hãy đặt giá trị âm.
Ví dụ 1 - Thêm tháng
Hãy xem ví dụ sau để triển khai phương thức DateTimeOffset.AddMonths():
using System;
public class Demo {
public static void Main() {
DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 08, 10, 4, 20, 10, new TimeSpan(-5, 0, 0));
Console.WriteLine("DateTimeOffset (before adding months) = {0}", dateTimeOffset);
DateTimeOffset res = dateTimeOffset.AddMonths(3);
Console.WriteLine("DateTimeOffset (after adding months) = {0}", res);
}
}
Đầu ra
Chương trình sẽ cho ra kết quả sau:
DateTimeOffset (before adding months) = 8/10/2019 4:20:10 AM -05:00 DateTimeOffset (after adding months) = 11/10/2019 4:20:10 AM -05:00
Ví dụ 2 - Trừ tháng
Ví dụ khác triển khai phương thức DateTimeOffset.AddMonths() với giá trị âm:
using System;
public class Demo {
public static void Main() {
DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 08, 10, 4, 20, 10, new TimeSpan(-5, 0, 0));
Console.WriteLine("DateTimeOffset (before subtracting months) = {0}", dateTimeOffset);
DateTimeOffset res = dateTimeOffset.AddMonths(-5);
Console.WriteLine("DateTimeOffset (after subtracting months) = {0}", res);
}
}
Đầu ra
Chương trình sẽ cho ra kết quả sau:
DateTimeOffset (before subtracting months) = 8/10/2019 4:20:10 AM -05:00 DateTimeOffset (after subtracting months) = 3/10/2019 4:20:10 AM -05:00