Generating a List of DateTime objects for a given date range
.NET, Programming No Comments »Here’s a little C# method I created recently. I needed a way to get all the dates between 2 dates as objects for use in a custom calendar control.
private static List<DateTime> CreateRange(DateTime startDate, DateTime endDate)
{
List<DateTime> r = new List<DateTime>();
int startYear = startDate.Year;
int startMonth = startDate.Month;
int endYear = endDate.Year;
int endMonth = endDate.Month;
const int day = 1;
const int totalMonths = 12;
int totalYears = endYear - startYear;
if (totalYears > 0)
{
endMonth += totalYears * totalMonths;
}
for (int year = startYear; year <= endYear; year++)
{
for (int mth = startMonth; mth <= endMonth; mth++)
{
int month = mth;
if (month > totalMonths)
{
month -= totalMonths;
}
r.Add(new DateTime(year, month, day));
if (mth == totalMonths)
{
endMonth -= totalMonths;
startMonth = 1;
break;
}
}
}
r.Reverse();
return r;
}
Now with the results of this method, you have a populated generic
List of DateTime objects between any 2 dates.
Recent Comments