How can I convert an Integer to localized month name in Java?

后端 未结 13 2129
眼角桃花
眼角桃花 2020-11-27 03:20

I get an integer and I need to convert to a month names in various locales:

Example for locale en-us:
1 -> January
2 -> February

Example for locale e

13条回答
  •  春和景丽
    2020-11-27 03:44

    tl;dr

    Month                             // Enum class, predefining and naming a dozen objects, one for each month of the year. 
    .of( 12 )                         // Retrieving one of the enum objects by number, 1-12. 
    .getDisplayName(
        TextStyle.FULL_STANDALONE , 
        Locale.CANADA_FRENCH          // Locale determines the human language and cultural norms used in localizing. 
    )
    

    java.time

    Since Java 1.8 (or 1.7 & 1.6 with the ThreeTen-Backport) you can use this:

    Month.of(integerMonth).getDisplayName(TextStyle.FULL_STANDALONE, locale);
    

    Note that integerMonth is 1-based, i.e. 1 is for January. Range is always from 1 to 12 for January-December (i.e. Gregorian calendar only).

提交回复
热议问题