Months in DatePickerDialog Android are displayed in a weird format

539 Views Asked by At

I recently upgraded my app to have a minSdkVersion of 26 and all the date picker dialogs are behaving very oddly. The DatePickerDialog is displaying the monnths from the calendar in the following format: enter image description here

As you can see the months are being displayed as "M + the number of the month" (01 being January - 12 being December), how can I revert this so the date can be displayed normally again? By normally I mean Oct instead of M10

Below is the code of my date picker dialog.

public static void showDatePickerDialog(Context context, DatePickerCallback datePickerCallback) {
        Calendar calendar = Calendar.getInstance();
        int buttonColor = ContextCompat.getColor(context, R.color.black);

        DatePickerDialog datePickerDialog = new DatePickerDialog(context, R.style.DatePickerDialogTheme, (view, year, month, dayOfMonth) -> {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            datePickerCallback.onDateSelected(calendar.getTime()); // the callback here is setting the date wherever we call this method

        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
        datePickerDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(buttonColor);
        datePickerDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(buttonColor);
    }
2

There are 2 best solutions below

1
vincent091 On

If you want the month in string you can use this

 
public String getMonth(int month) {
    return new DateFormatSymbols().getMonths()[month-1];
}

And for the problem of M you can use a Local in your calendar instance :


Calendar c = Calendar.getInstance(Locale.getDefault());
0
zurakos On

Finally, I found a workaround for the months being displayed as "M + number". I just had to set up my locale to be of the English language. Below is the method that gets the proper locale to be injected later on in a calendar instance:

// get the english locale
public static Locale getLocaleForCalendarInstance(Context context) {
        Locale locale = new Locale("en");
        Locale.setDefault(locale);
        Configuration config = context.getResources().getConfiguration();
        config.locale = locale;
        context.getResources().updateConfiguration(config,
                context.getResources().getDisplayMetrics());
        return locale;
    }

//then set the locale in your calendar instance
Calendar calendar = Calendar.getInstance(getLocaleForCalendarInstance(context));


Months are now displayed correctly again in the Date Picker Dialog :)