當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# DateTime.AddMonths()用法及代碼示例

此方法用於返回新的DateTime,該日期將指定的月數添加到此實例的值。

用法:

public DateTime AddMonths (int months);

在這裏,月數是月數。 months參數可以是負數或正數。


返回值:此方法返回一個對象,該對象的值是此實例和月份表示的日期和時間的總和。

異常:如果生成的DateTime小於MinValue或大於MaxValue,則此方法將引發ArgumentOutOfRangeException。 or 小於-120,000或大於120,000。

以下示例程序旨在說明上述方法的用法:

示例1:

// C# program to demonstrate the 
// DateTime.AddMonths(Int32) Method 
using System; 
  
class GFG { 
  
// Main Method 
public static void Main() 
{ 
  
    // Creating a DateTime object 
    DateTime d1 = new DateTime(2018, 4, 17); 
  
    for (int i = 0; i <= 10; i++) 
    { 
  
        // using the method 
        Console.WriteLine(d1.AddMonths(i).ToString("d")); 
          
    } 
      
    Console.WriteLine("In Leap Years:"); 
      
    // Creating a DateTime object 
    // by taking a leap year 
    // It is 31st March 2016 
    DateTime d2 = new DateTime(2016, 03, 31); 
      
    // taking a month value 
    int m = 1; 
      
    // using the method 
    // Result will be 30 April 2016 
    Console.WriteLine(d2.AddMonths(m).ToString("d")); 
      
      
} 
}

輸出:

04/17/2018
05/17/2018
06/17/2018
07/17/2018
08/17/2018
09/17/2018
10/17/2018
11/17/2018
12/17/2018
01/17/2019
02/17/2019
In Leap Years:
04/30/2016

示例2:

// C# program to demonstrate the 
// DateTime.AddMonths(Int32) Method 
using System; 
  
class GFG { 
  
// Main Method 
public static void Main() 
{ 
  
    // Creating a DateTime object 
    // taking MaxValue 
    DateTime d1 = DateTime.MaxValue; 
  
    // taking a month MaxValue 
    int m = 12005; 
  
    // using the method will  
    // give an runtime error 
    // as months parameter is 
    // greater than 12000 
    Console.WriteLine(d1.AddMonths(m).ToString("d")); 
} 
}

運行時錯誤:

Unhandled Exception:
System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime.
Parameter name: months

注意:

  • 此方法不會更改此DateTime對象的值。而是返回一個新的DateTime對象,其值是此操作的結果。
  • 這將考慮leap年和一個月中的天數來計算得出的月份和年份,然後調整得出的DateTime對象的日期部分。
  • 生成的DateTime對象的time-of-day部分與此實例相同。

參考:



相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 DateTime.AddMonths() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。