Iterate over each Day between StartDate and EndDate [duplicate]

Solution 1:

for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
{
    ...
}

The .Date is to make sure you have that last day, like in the example.

Solution 2:

An alternative method that might be more reusable is to write an extension method on DateTime and return an IEnumerable.

For example, you can define a class:

public static class MyExtensions
{
    public static IEnumerable EachDay(this DateTime start, DateTime end)
    {
        // Remove time info from start date (we only care about day). 
        DateTime currentDay = new DateTime(start.Year, start.Month, start.Day);
        while (currentDay <= end)
        {
            yield return currentDay;
            currentDay = currentDay.AddDays(1);
        }
    }
}

Now in the calling code you can do the following:

DateTime start = DateTime.Now;
DateTime end = start.AddDays(20);
foreach (var day in start.EachDay(end))
{
    ...
}

Another advantage to this approach is that it makes it trivial to add EachWeek, EachMonth etc. These will then all be accessible on DateTime.