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

后端 未结 13 2142
眼角桃花
眼角桃花 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:33

    Apparently in Android 2.2 there is a bug with SimpleDateFormat.

    In order to use month names you have to define them yourself in your resources:

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

    And then use them in your code like this:

    /**
     * Get the month name of a Date. e.g. January for the Date 2011-01-01
     * 
     * @param date
     * @return e.g. "January"
     */
    public static String getMonthName(Context context, Date date) {
    
        /*
         * Android 2.2 has a bug in SimpleDateFormat. Can't use "MMMM" for
         * getting the Month name for the given Locale. Thus relying on own
         * values from string resources
         */
    
        String result = "";
    
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int month = cal.get(Calendar.MONTH);
    
        try {
            result = context.getResources().getStringArray(R.array.month_names)[month];
        } catch (ArrayIndexOutOfBoundsException e) {
            result = Integer.toString(month);
        }
    
        return result;
    }
    

提交回复
热议问题