0

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.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
aleczandru
  • 5,319
  • 15
  • 62
  • 112
  • 2
    http://stackoverflow.com/questions/248273/count-number-of-mondays-in-a-given-date-range - second answer down. Additionally, if you need help in creating the range of dates - http://stackoverflow.com/questions/3738748/create-an-array-or-list-of-all-dates-between-two-dates – TVOHM Mar 05 '16 at 12:24
  • [Using Linq](http://stackoverflow.com/a/31247959/205233) (direct link to answer mentioned by @TVOHM) – Filburt Mar 05 '16 at 12:28
  • Hah, didn't see that one - that's actually quite a nice solution. – TVOHM Mar 05 '16 at 12:29

2 Answers2

3

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;
}
Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
0

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;
}
NoName
  • 7,940
  • 13
  • 56
  • 108