我如何在一个月内获得所有工作日和日期

时间:2012-10-15 20:42:16

标签: c# asp.net datetime

我试图获取所选月份的所有工作日以及周一或周二等日期等等?这怎么可能?是否有一个我不知道的内置函数?

这是在C#2.0,使用VS 2005的asp.net

2 个答案:

答案 0 :(得分:4)

我不保证闰年,夏令时跳跃,特殊日子,Shanghai 1927等。

public List<DateTime> getWeekdatesandDates(int Month, int Year)
{
    List<DateTime> weekdays = new List<DateTime>();

    DateTime firstOfMonth = new DateTime(Year, Month, 1);

    DateTime currentDay = firstOfMonth;
    while (firstOfMonth.Month == currentDay.Month)
    {
        DayOfWeek dayOfWeek = currentDay.DayOfWeek;
        if (dayOfWeek != DayOfWeek.Saturday && dayOfWeek != DayOfWeek.Sunday)
            weekdays.Add(currentDay);

        currentDay = currentDay.AddDays(1);
    }

    return weekdays;
}

生成的DateTime对象具有DayOfWeek属性,您可以检查它是否是星期一到星期五。

答案 1 :(得分:1)

这应该有效

private List<DateTime> getWeekDayDates(int month, int year)
{
    List<DateTime> weekdays = new List<DateTime>();
    DateTime basedt = new DateTime(year, month, 1);
    while ((basedt.Month == month) && (basedt.Year == year))
    {
        if (basedt.DayOfWeek == (DayOfWeek.Monday | DayOfWeek.Tuesday | DayOfWeek.Wednesday | DayOfWeek.Thursday | DayOfWeek.Friday))
        {
            weekdays.Add(new DateTime(basedt.Year, basedt.Month, basedt.Day));
        }
        basedt = basedt.AddDays(1);
    }
    return weekdays;
}

然后,您可以从每个DateTime获取所需的任何信息。