DateTime.AddMonths(Int32) 方法

定义

返回一个新 DateTime 值,它将指定的月份数添加到此实例的值。

public:
 DateTime AddMonths(int months);
public DateTime AddMonths(int months);
member this.AddMonths : int -> DateTime
Public Function AddMonths (months As Integer) As DateTime

参数

months
Int32

几个月。 参数 months 可以是负数或正数。

返回

一个对象,其值为此实例所表示的日期和时间之和。months

例外

生成的结果 DateTime 小于 DateTime.MinValue 或大于 DateTime.MaxValue

-或-

months 小于 -120,000 或大于 120,000。

示例

以下示例在 2015 年 12 月的最后一天将介于零到 15 个月之间。 在这种情况下,AddMonths 方法返回每个月最后一天的日期,并成功处理 leap 年。

using System;

public class Example
{
   public static void Main()
   {
      var dat = new DateTime(2015, 12, 31);
      for (int ctr = 0; ctr <= 15; ctr++)
         Console.WriteLine(dat.AddMonths(ctr).ToString("d"));
   }
}
// The example displays the following output:
//       12/31/2015
//       1/31/2016
//       2/29/2016
//       3/31/2016
//       4/30/2016
//       5/31/2016
//       6/30/2016
//       7/31/2016
//       8/31/2016
//       9/30/2016
//       10/31/2016
//       11/30/2016
//       12/31/2016
//       1/31/2017
//       2/28/2017
//       3/31/2017
open System

let dat = DateTime(2015, 12, 31)
for i = 0 to 15 do
    printfn $"{dat.AddMonths i:d}"

// The example displays the following output:
//       12/31/2015
//       1/31/2016
//       2/29/2016
//       3/31/2016
//       4/30/2016
//       5/31/2016
//       6/30/2016
//       7/31/2016
//       8/31/2016
//       9/30/2016
//       10/31/2016
//       11/30/2016
//       12/31/2016
//       1/31/2017
//       2/28/2017
//       3/31/2017
Module Example
   Public Sub Main()
      Dim dat As Date = #12/31/2015#
      For ctr As Integer = 0 To 15
         Console.WriteLine(dat.AddMonths(ctr).ToString("d"))
      Next
   End Sub
End Module
' The example displays the following output:
'       12/31/2015
'       1/31/2016
'       2/29/2016
'       3/31/2016
'       4/30/2016
'       5/31/2016
'       6/30/2016
'       7/31/2016
'       8/31/2016
'       9/30/2016
'       10/31/2016
'       11/30/2016
'       12/31/2016
'       1/31/2017
'       2/28/2017
'       3/31/2017

注解

此方法不会更改此 DateTime 对象的值。 而是返回一个新 DateTime 对象,该对象的值是此操作的结果。

该方法 AddMonths 将计算生成的月份和年份,并考虑一个月内的 leap 年和天数,然后调整生成的 DateTime 对象的日期部分。 如果生成的日期在生成的月份中不是有效日期,则使用生成的月份的最后一个有效日期。 例如,3 月 31 日 + 1 个月 = 4 月 30 日,3 月 31 日 - 1 个月 = 2 月 28 日(对于非跃年)和 2 月 29 日的跃年。

生成的 DateTime 对象的一天时间部分与此实例保持一致。

适用于