C# 如何获取特定月份和年份的天数

C# 如何获取特定月份和年份的天数,c#,.net,C#,.net,我有一个方法,它通过两个参数:月份和年份 我将这样调用此方法:MonthDates(2010年1月) 如何计算特定月份和年份的天数?您是指一个月的天数吗 System.DateTime.DaysInMonth(int year, int month) 等等………你可以从DateTime获得很多东西。现在,如果你想把所有的日子都作为DateTime的集合,那么: public static IEnumerable<DateTime> daysInMonth(int year, int

我有一个方法,它通过两个参数:月份和年份

我将这样调用此方法:MonthDates(2010年1月)


如何计算特定月份和年份的天数?

您是指一个月的天数吗

System.DateTime.DaysInMonth(int year, int month)

等等………你可以从DateTime获得很多东西。现在,如果你想把所有的日子都作为DateTime的集合,那么:

public static IEnumerable<DateTime> daysInMonth(int year, int month)
{
    DateTime day = new DateTime(year, month, 1);
    while (day.Month == month)
    {
        yield return day;
        day = day.AddDays(1);
    }
}
公共静态IEnumerable daysInMonth(整数年,整数月)
{
DateTime day=新的日期时间(年、月、1);
while(day.Month==月)
{
收益率回归日;
天=天。添加天(1);
}
}
用途是:

IEnumerable<DateTime> days = daysInMonth(2010, 07);
IEnumerable days=daysInMonth(2010,07);

尝试声明如下所示的枚举,而不是字符串

public enum Month
{
   January = 1,
   February,
   March,
   .... so on
}
然后将其传递给您的函数,并在函数中使用以下内容

return System.DateTime.DaysInMonth(year, month);

尝试使用整数而不是字符串,因为它将减少解析字符串的开销。

我将字符串作为字符串传递parameter@ravidotnet-你能编辑这个问题吗?问题是如何解析这些字符串,将它们转换为数字?这是您在读取数据后的第一阶段要做的事情,您不想传递字符串。我将传递为MOnthDates(janauary,2010),它将天数返回为1,2,3,……31天如果问题是关于解析字符串,请参见以下内容:
public enum Month
{
   January = 1,
   February,
   March,
   .... so on
}
return System.DateTime.DaysInMonth(year, month);