获取工作日DateTime两个日期的列表

时间:2013-08-14 15:59:31

标签: c# .net datetime

我试图获得两个日期之间的工作日清单,但我只用了一个月。

var workingDays = Enumerable.Range(1, daysInMonth)
                          .Where(d =>
                              !weekends.Contains(new DateTime(last30Days.Year, last30Days.Month, d).DayOfWeek)).ToList();

但是这样我只有一个月的假期。

1 个答案:

答案 0 :(得分:9)

从一个函数开始,以获取两个日期之间的所有日期:

public static IEnumerable<DateTime> DaysBetween(DateTime start, DateTime end)
{
    var current = start;
    if (current != current.Date) //handle the case where the date isn't already midnight
        current = current.AddDays(1).Date;
    while (current < end)
    {
        yield return current;
        current = current.AddDays(1);
    }
}

然后过滤掉非工作日:

public static IEnumerable<DateTime> WorkDayBetween(DateTime start, DateTime end)
{
    return DaysBetween(start, end)
        .Where(date => IsWorkDay(date));
}

//feel free to use alternate logic here, or to account for holidays, etc.
private static bool IsWorksDay(DateTime date)
{
    return date.DayOfWeek != DayOfWeek.Saturday
                    && date.DayOfWeek != DayOfWeek.Sunday;
}