Reputation: 728
I want to calculate a list of months in specified date range.
For instance:
DateTime StartDate = 24 - 11 - 2014;
DateTime EndDate = 24 - 11 - 2016;
I want to calculate all the months between starting and ending date with names of months.
Upvotes: 0
Views: 188
Reputation: 12491
Here you go a static function that do what you need:
public static Dictionary<int, string> MonthsBetween(
DateTime startDate,
DateTime endDate)
{
DateTime iterator;
DateTime limit;
if (endDate > startDate)
{
iterator = new DateTime(startDate.Year, startDate.Month, 1);
limit = endDate;
}
else
{
iterator = new DateTime(endDate.Year, endDate.Month, 1);
limit = startDate;
}
var dateTimeFormat = CultureInfo.CurrentCulture.DateTimeFormat;
var result = new Dictionary<int, string>();
while (iterator <= limit)
{
if (!result.Keys.Contains(iterator.Month))
result.Add(iterator.Month, dateTimeFormat.GetMonthName(iterator.Month));
iterator = iterator.AddMonths(1);
}
return result;
}
you can use it like this:
DateTime startDate = new DateTime(2014, 11, 24);
DateTime endDate = new DateTime(2016, 11, 24);
var list = Program.MonthsBetween(startDate, endDate);
list
variable contains dictionary with month int value and name according to CultureInfo.CurrentCulture
of your program.
I get this function from this answer and slightly modify it.
Upvotes: 0