How-To loop through a Date Range

Programming C#

The convenience way would be a FOR...NEXT loop:

static void Main(string[] args)
{
DateTime startDate = new DateTime(2020, 07, 01);
DateTime endDate = new DateTime(2020, 09, 30);

for (DateTime dtm = startDate; dtm <= endDate; dtm = dtm.AddDays(1))
{
Console.WriteLine(dtm);
}

Console.ReadLine();
}

Please notice that a construct like

for (DateTime dtm = startDate; dtm <= endDate; dtm.AddDays(1))
{
}

would fail because the counter variable dtm would never be increased.

Or you could use a WHILE loop:

DateTime startDate = new DateTime(2020, 07, 01);
DateTime endDate = new DateTime(2020, 09, 30);
DateTime dtm = startDate;

while(dtm <= endDate)
{
Console.WriteLine(dtm);
dtm = dtm.AddDays(1);
}

Console.ReadLine();

In our example we increase the date by one day which will give us a range of days within the given borders of start and end date (both inclusive).  Of course you could also increase it by one hour or 30 minutes or 7 days or any other cyclically value.