获取两个日期之间某个工作日的日期

时间:2016-03-05 12:21:31

标签: c# .net datetime

我收到了开始和结束DateTime

由此,我想创建这两个日期之间所有日期的List<DateTime>,但仅限于指定的工作日,例如星期一。

2 个答案:

答案 0 :(得分:0)

您可以按Create an array or List of all dates between two dates

中的说明生成日期列表
public List<DateTime> GetDatesBetween(DateTime start, DateTime end)
{
    var dates = Enumerable.Range(0, 1 + end.Subtract(start).Days)
                          .Select(offset => start.AddDays(offset))
                          .ToList();
    return dates;
}

现在过滤此列表仅包含您感兴趣的工作日同样微不足道的是,只选择日期Where() DayOfWeek property是所请求的工作日之一:

public List<DateTime> GetDatesBetween(DateTime start, DateTime end, params DayOfWeek[] weekdays)
{
    bool allDays = weekdays == null || !weekdays.Any();

    var dates = Enumerable.Range(0, 1 + end.Subtract(start).Days)
                          .Select(offset => start.AddDays(offset))
                          .Where(d => allDays || weekdays.Contains(d.DayOfWeek))
                          .ToList();
    return dates;
}

答案 1 :(得分:0)

Bellow函数返回List<DateTime>包含从startDateendDate的所有日期dayOfWeek

public static List<DateTime> Get_DayofWeek_DatesBetween(DateTime startDate, DateTime endDate, DayOfWeek dayOfWeek)
{
    List<DateTime> list = new List<DateTime>();

    // Total dates in given range. "+ 1" include endDate
    double totalDates = (endDate.Date - startDate.Date).TotalDays + 1;

    // Find first "dayOfWeek" date from startDate
    int i = dayOfWeek - startDate.DayOfWeek;
    if (i < 0) i += 7;

    // Add all "dayOfWeek" dates in given range
    for (int j = i; j < totalDates; j += 7) list.Add(startDate.AddDays(j));

    return list;
}