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 月的最後一天加上 0 到 15 個月。 在此情況下,AddMonths 方法會傳回每個月最後一天的日期,並成功處理閏年。

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 會計算產生的月份和年份,並考慮閏年和一個月中的天數,然後調整結果 DateTime 物件的日期部分。 如果產生的日期不是結果月份的有效日期,則會使用結果月份的最後一個有效日。 例如,3 月 31 日 + 1 個月 = 4 月 30 日,而 3 月 31 日 - 1 個月 = 非閏年 2 月 28 日,而 2 月 29 日則為閏年。

結果 DateTime 物件的一天時間部分會維持與這個實例相同的狀態。

適用於