How to calculate list of months in specified date range in UmAlQuraCalendar

179 views Asked by At

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.

1

There are 1 answers

0
teo van kot On

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.