📜  C#中的DateTime.DaysInMonth()方法

📅  最后修改于: 2021-05-29 20:23:40             🧑  作者: Mango

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

句法:

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

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

异常:如果月份小于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);
    }
}

运行时错误:

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.datetime.daysinmonth?view=netframework-4.7.2