Search
Close this search box.

C# code to get generic list of dates between starting and ending date

This code snippet will return a generic list of DateTime containing the dates between a starting date and ending date:

private List<DateTime> GetDateRange(DateTime StartingDate,
                                    DateTime EndingDate) {
  if (StartingDate > EndingDate) {
    return null;
  }
  List<DateTime> rv = new List<DateTime>();
  DateTime tmpDate = StartingDate;
  do {
    rv.Add(tmpDate);
    tmpDate = tmpDate.AddDays(1);
  } while (tmpDate <= EndingDate);
  return rv;
}

To view this code in action, copy and paste the following code into SnippetCompiler:

DateTime StartingDate = DateTime.Parse("02/25/2007");
DateTime EndingDate = DateTime.Parse("03/06/2007");
foreach (DateTime date in GetDateRange(StartingDate,EndingDate))
{
   WL(date.ToShortDateString()); 
}

And it will return:
2/25/2007
2/26/2007
2/27/2007
2/28/2007
3/1/2007
3/2/2007
3/3/2007
3/4/2007
3/5/2007
3/6/2007

Technorati tags: C#.NETDateTimeCode

This article is part of the GWB Archives. Original Author: Tim Hibbard

Related Posts