Month name as a string

前端 未结 11 2166
悲哀的现实
悲哀的现实 2020-11-27 02:49

I\'m trying to return the name of the month as a String, for instance \"May\", \"September\", \"November\".

I tried:

int month = c.get(Calendar.MONTH         


        
11条回答
  •  一向
    一向 (楼主)
    2020-11-27 03:26

    I would recommend to use Calendar object and Locale since month names are different for different languages:

    // index can be 0 - 11
    private String getMonthName(final int index, final Locale locale, final boolean shortName)
    {
        String format = "%tB";
    
        if (shortName)
            format = "%tb";
    
        Calendar calendar = Calendar.getInstance(locale);
        calendar.set(Calendar.MONTH, index);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
    
        return String.format(locale, format, calendar);
    }
    

    Example for full month name:

    System.out.println(getMonthName(0, Locale.US, false));
    

    Result: January

    Example for short month name:

    System.out.println(getMonthName(0, Locale.US, true));
    

    Result: Jan

提交回复
热议问题