简体   繁体   中英

Get dates given a start date an end date and day of week

Given a start date (DateTime), an end date (DateTime) and a list of DayOfWeek(s). How to get all the matching dates :

Example :

StartDate : "06/17/2016" 
EndDate : "06/30/2016" 
DayOfWeek(s) : [0(Monday), 1(Tuesday), 4(Friday)]

The wanted result is :

Dates = ["06/17/2016", "06/20/2016", "06/21/2016", "06/24/2016", "06/27/2016", "06/28/2016"]

This will return you list of all dates between the startDate and EndDate, that belong to the given enum of dayOfWeek:

var allDays = Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d));
var Dates = allDays.Where(dt => dayOfWeek.Contains(dt.DayOfWeek)).ToList();

yet another possible solution, I think this is simple to understand and debug, even if it cost more lines and maybe little more resources than other possible solutions:

    var startDate = new DateTime(2016, 06, 17);
    var endDate = new DateTime(2016, 06, 30);

    DayOfWeek[] daysOfWeek = { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Friday };

    List<DateTime> dates = new List<DateTime>();
    if (endDate >= startDate)
    {
        var tmp = startDate;
        tmp = tmp.AddDays(1); //I notice you didn't add 06/17/2016 that is friday, if you want to add it, just remove this line
        do
        {
            if (daysOfWeek.Contains(tmp.DayOfWeek))
                dates.Add(tmp);
            tmp = tmp.AddDays(1);
        }
        while (tmp <= endDate); //If you don't want to consider endDate just change this line into while (tmp < endDate); 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM