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

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

问题描述:

我收到一个开始和结束 DateTime

I receive a start and end DateTime.

从此,我想在这两个日期之间的所有日期中创建一个列表< DateTime> ,但只在指定的工作日,如星期一。

From this, I want to create a List<DateTime> of all the dates that are between these two dates, but only on specified weekdays, such as the Monday.

Bellow函数返回一个列表< DateTime&gt ; 包含从 startDate endDate 中的所有日期给予 dayOfWeek

Bellow function return a List<DateTime> contains all dates from startDate to endDate have given 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;
}