获取工作日日期时间两个日期的列表

本文关键字:日期 两个 列表 工作日 时间 获取 | 更新日期: 2023-09-27 18:27:37

我想得到两个日期之间的工作日列表,但我只得到了一个月的时间。

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

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

获取工作日日期时间两个日期的列表

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

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;
}