当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# DateTime.DaysInMonth()用法及代码示例


此方法返回指定月份和年份中的天数。即使公历不是当前文化的当前日历,此方法也始终将月份和年份解释为公历的月份和年份。

用法:

public static int DaysInMonth (int year, int month);

返回值:此方法返回指定年份的月份中的天数。例如,如果2月的月份等于2,则返回值将为28或29,具体取决于年份是否为leap年。


异常:如果月份小于1或大于12或年份小于1或大于9999,则此方法将提供ArgumentOutOfRangeException。

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

示例1:

// C# code to demonstrate the 
// DaysInMonth(Int32, Int32) Method 
using System; 
  
class GFG { 
  
    // Main Method 
    static void Main() 
    { 
  
        // taking month values 
        int Dec = 12; 
        int Feb = 2; 
  
        // using the method 
        int daysindec = DateTime.DaysInMonth(2008, Dec); 
  
        Console.WriteLine(daysindec); 
  
        // daysinfeb1 gets 29 because the 
        // year 2016 was a leap year. 
        int daysinfeb1 = DateTime.DaysInMonth(2016, Feb); 
  
        Console.WriteLine(daysinfeb1); 
  
        // daysinfeb2 gets 28 because 
        // the year 2018 was not a leap year. 
        int daysinfeb2 = DateTime.DaysInMonth(2018, Feb); 
  
        Console.WriteLine(daysinfeb2); 
    } 
}

输出:

31
29
28

示例2:

// C# code to demonstrate the 
// DaysInMonth(Int32, Int32) Method 
using System; 
  
class GFG { 
  
    // Main Method 
    static void Main() 
    { 
  
        // taking month and year's value 
        int y = 10000; 
        int m = 7; 
  
        // using the method will give error 
        // as the value of the year is greater 
        // than 10000 
        int res = DateTime.DaysInMonth(y, m); 
  
        Console.WriteLine(res); 
    } 
}

运行时错误:

Unhandled Exception:
System.ArgumentOutOfRangeException: Year must be between 1 and 9999.
Parameter name: year

参考:



相关用法


注:本文由纯净天空筛选整理自Kirti_Mangal大神的英文原创作品 DateTime.DaysInMonth() Method in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。