Reputation: 1207
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"]
Upvotes: 0
Views: 713
Reputation: 2970
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();
Upvotes: 2
Reputation: 495
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);
}
Upvotes: 2