0

我试图获取两个日期之间的工作日列表,但我只是从一个月开始。

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

但这样我只能得到一个特定的月份。

4

1 回答 1

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;
}
于 2013-08-14T16:03:42.657 回答