DateTime.AddMonths(Int32) 方法

定義

傳回新的 DateTime,將這個執行個體的值加上指定的月數。

C#
public DateTime AddMonths(int months);

參數

months
Int32

月份數。 months 參數可以是負數或正數。

傳回

物件,其值為這個執行個體所表示日期和時間加上 months 的總和。

例外狀況

產生的 DateTime 小於 DateTime.MinValue 或大於 DateTime.MaxValue

-或-

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

範例

下列範例會在 2015 年 12 月的最後一天加上 0 到 15 個月。 在此情況下,AddMonths 方法會傳回每個月最後一天的日期,並成功處理閏年。

C#
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

備註

這個方法不會變更這個 DateTime 物件的值。 相反地,它會傳回新的 DateTime 物件,其值為這個作業的結果。

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

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

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0