英語で読む

次の方法で共有


DateTime.AddMonths(Int32) メソッド

定義

このインスタンスの値に、指定された月数を加算した新しい DateTime を返します。

C#
public DateTime AddMonths(int months);

パラメーター

months
Int32

月数。 months パラメーターは、正または負のどちらの場合もあります。

戻り値

このインスタンスで表された日付と時刻と months の合計を値とするオブジェクト。

例外

結果 DateTimeDateTime.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