Iterate Through a Date Range.

When you need to write logic for each specific date in a date range. One way to iterate through the days is using something like this method.

private IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
     for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
     {
          yield return day;
     }
}

This method could then be called like:

foreach (DateTime day in EachDay(StartDate, EndDate))

If  you have not used yield before there are many great articles out there already that can explain in more detail, however it basically is returning each value per cycle before going back to the loop. So this would talk to this method, return a single day before returning to the next day.

Source

Posted in C#

Leave a Reply