Search code examples
c#datetimecalendarglobalization

How to determine upcoming months relative to a given month in any calendar?


How can I find out the upcoming months relative to a given month according to the calendar that I select?

Meaning I selected the Gregorian calendar and the given month is September, a list of the following months will appear:

[September, October, November, December]

If the Hijri calendar is selected and the current month is: Dhu al-Qa’dah, a list of the remaining months will appear, which are:

[Dhul Qi'dah, Dhul Hijjah]

I used the following reference to make the code but it didn't work

System.Globalization.CultureInfo(DateLangCulture, false).DateTimeFormat

Solution

  • In .NET Framework, month names are based on a culture. If I understand your question clearly, you want to select some "Calendar" and want to list some months of it. I think there is a problem with this approach because different cultures might use the same calendar and these different cultures might have different month names.

    For example, let's take GregorianCalendar, if you want to list english-based month names, you can clearly use a culture like InvariantCulture which you will get January, February, March etc.. But on the other side, Turkish culture (tr-TR) also uses GregorianCalendar as a calendar but it's month names are like Ocak, Şubat, Mart etc. That means, even if you choose a "right" CultureInfo for your calendar, you might have a language problem as well. I hope you understand my concern. A calendar months might have a different languages since they are belongs on cultures.

    If you really want to get these based on calendars, you can create a CultureInfo which uses selected Calendar and list their MonthNames property as a string array which starts with the current month.

    For example; for GregorianCalendar, you can use InvariantCulture which month names are;

    CultureInfo.InvariantCulture.DateTimeFormat.MonthNames
    

    January February March April May June July August September October November December

    and for HijriCalendar, you can use ar-SA culture (it uses UmAlQuraCalendar which is close enough to HijriCalendar in my opinion) which month names are;

    (new CultureInfo("ar-SA")).DateTimeFormat.MonthNames
    

    محرم صفر ربيع الأول ربيع الآخر جمادى الأولى جمادى الآخرة رجب شعبان رمضان شوال ذو القعدة ذو الحجة

    which they can be translated to English as;

    enter image description here

    You can get the current month number as;

    var currentMonthNo = Datetime.Now.Month;
    

    then you can start to iterate from its previous index (since array start index 0) to the end of the array (be aware, there are some calendars that have 13 months, that's why for 12 month cultures the 13th element of the array is an empty string).