I receive a start and end 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.
I receive a start and end 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.
You can generate a list of dates as explained in 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;
}
Now to filter this list to only include weekdays you're interested in is equally trivial by selecting only dates Where()
the DayOfWeek property is one of the requested weekdays:
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;
}
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;
}