Search code examples
javacalendar

Get name of the month in Java


I wanna programmatically convert an integer in the range 1-12 to corresponding month name. (e.g. 1 -> January, 2 -> February) etc using Java Calendar class in one statement.

Note : I want to do it using Java Calendar class only. Don't suggest any switch-case or string array solution.

Thanks.


Solution

  • The Calendar class is not the best class to use when it comes obtaining the localized month name in one statement.

    The following is an example of obtaining the month name of a desired month specified by a int value (where January is 1), using only the Calendar class:

    // Month as a number.
    int month = 1;
    
    // Sets the Calendar instance to the desired month.
    // The "-1" takes into account that Calendar counts months
    // beginning from 0.
    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, month - 1);
    
    // This is to avoid the problem of having a day that is greater than the maximum of the
    // month you set. c.getInstance() copies the whole current dateTime from system 
    // including day, if you execute this on the 30th of any month and set the Month to 1 
    // (February) getDisplayName will get you March as it automatically jumps to the next              
    // Month
    c.set(Calendar.DAY_OF_MONTH, 1);    
    
    // Returns a String of the month name in the current locale.
    c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
    

    The above code will return the month name in the system locale.

    If another locale is required, one can specify another Locale by replacing the Locale.getDefault() with a specific locale such as Locale.US.