📅  最后修改于: 2023-12-03 15:00:16.578000             🧑  作者: Mango
DateTime.DaysInMonth()
方法可用于获取指定年份和月份中的天数。
public static int DaysInMonth(int year, int month);
year
:要检查的年份。必须为 1 到 9999 之间的整数。month
:要检查的月份。必须为 1 到 12 之间的整数。指定年份和月份的天数。
下面是一个示例,该示例演示如何使用 DaysInMonth()
方法来获取指定年份和月份的天数。
using System;
class Program
{
static void Main()
{
int daysInFebruary = DateTime.DaysInMonth(2021, 2);
Console.WriteLine("February 2021 had {0} days.", daysInFebruary);
int daysInJuly = DateTime.DaysInMonth(2021, 7);
Console.WriteLine("July 2021 had {0} days.", daysInJuly);
}
}
输出:
February 2021 had 28 days.
July 2021 had 31 days.
year
或 month
参数的值超出了有效范围,则会引发 ArgumentOutOfRangeException
异常。DaysInMonth()
方法之前检查了 year
和 month
参数的有效性,则可以避免引发异常。例如:int year = 2021;
int month = 13;
if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
{
int days = DateTime.DaysInMonth(year, month);
Console.WriteLine("This month has {0} days.", days);
}
else
{
Console.WriteLine("Invalid year or month.");
}