C#中的DateTime.AddMonths()方法
C#中的DateTime.AddMonths()方法用于将指定的月数添加到此实例的值。
语法
以下是语法-
public DateTime AddMonths (int val);
上面的Val是月数。如果要减去月份,则将其设置为负数。
示例
现在让我们看一个实现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); } }
输出结果
这将产生以下输出-
Initial DateTime = 15 May 2019, 05:15:25 New DateTime (After adding months) = 15 October 2019, 05:15:25
示例
现在让我们来看另一个实现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); } }
输出结果
这将产生以下输出-
Initial DateTime = 20 August 2019, 03:30:50 New DateTime (After subtracting months) = 20 June 2019, 03:30:50