Search code examples
androidandroid-datepicker

simpledateformat localizing wrong months name list


I created Month-year picker.It was working fine but from couple of days it's creating problem. I was fetching months name list using Simpledateformat localization. But now it's repeating some months name. I don't know why? please help me out of it. This is my code:

private static String[] monthsList() {
    if (MONTHS_LIST == null) {
        int[] months = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
        String[] stringMonths = new String[months.length];
        for (int i = 0; i < months.length; i++) {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat monthDate = new SimpleDateFormat(MONTH_FORMAT, Locale.US);
            calendar.set(Calendar.MONTH, months[i]);
            String monthName = monthDate.format(calendar.getTime());
            stringMonths[i] = capitalize(monthName);
        }
        MONTHS_LIST = stringMonths;
    }
    return MONTHS_LIST;
}

Output:

it's the screenshot of Month picker, in which it showing march in place of Feb

it's the screenshot of Month picker, in which it showing march in place of Feb


Solution

  • I do little bit changes inside your code and now it is giving me the accurate name of months. I also put Log.e for check the name.

    private static String[] monthsList() {
        if (MONTHS_LIST == null) {
            int[] months = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
            String[] stringMonths = new String[months.length];
            for (int i = 0; i < months.length; i++) {
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat monthDate = new SimpleDateFormat("MMMM");
                calendar.set(Calendar.MONTH, months[i]);
                String monthName = monthDate.format(calendar.getTime());
                stringMonths[i] = capitalize(monthName);
    
                Log.e("month name",monthName);
            }
            MONTHS_LIST = stringMonths;
        }
        return MONTHS_LIST;
    }
    

    Below I put log screenshot for proof. enter image description here