0

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.

slavoo
  • 5,798
  • 64
  • 37
  • 39
Salman Ullah Khan
  • 730
  • 10
  • 29

1 Answers1

0

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.

Community
  • 1
  • 1
teo van kot
  • 12,350
  • 10
  • 38
  • 70