androidtimezonejava-timeandroid-calendarmaterialdatepicker

MaterialDatePicker returns incorrect date after selection


For some unknown reason, MaterialDatePicker returns incorrect date after selection. For example, user is in Mexico region with timezone: America/Tijuana. When he selects in visual representation: 2021-10-05, in resulting text I have -1 day, 2021-10-04. For RU region everything works fine. Here is the code:

public void startDateSelectionPicker() {
    try {
        MaterialDatePicker<Long> picker = MaterialDatePicker.Builder.datePicker()
                .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
                .setTheme(R.style.CustomDatePickerDialog)
                .build();

        picker.addOnPositiveButtonClickListener(selection -> {
            TimeZone t = TimeZone.getDefault();
            Calendar c1 = Calendar.getInstance();
            c1.setTimeInMillis(selection);
            c1.setTimeZone(TimeZone.getDefault());

//here I need to receive correct date, but receiving -1 from originally selected date.

            String date = ToolsManager.calendarToDate(this, c1, "yyyy-MM-dd");
        });
        picker.show(getSupportFragmentManager(), picker.getTag());
    } catch (IllegalArgumentException e) {
    }
}

public static String calendarToDate(Context context, Calendar calendar, String dateFormat) {
        if (calendar == null) {
            return null;
        }

        Locale locale = context.getResources().getConfiguration().locale;
        DateFormat df = new SimpleDateFormat(dateFormat, locale);

        return df.format(calendar.getTime());
    }

And also when I am setting: .setSelection(MaterialDatePicker.todayInUtcMilliseconds())

it display 18 of October on calendar, but really today is 20 of Octobeer.


Solution

  • I have solved this issue with such code:

    public void startDateSelectionPicker() {
            try {
                MaterialDatePicker<Long> picker = MaterialDatePicker.Builder.datePicker()
                        .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
                        .setTheme(R.style.CustomDatePickerDialog)
                        .build();
    
                picker.addOnPositiveButtonClickListener(selection -> {
                    Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
                    utc.setTimeInMillis(selection);
                    String date = ToolsManager.calendarToDate(this, utc, ToolsManager.LETY_FILTRATION_DATE_FORMAT);
                    binding.textview.setText(date);
                });
                picker.show(getSupportFragmentManager(), picker.getTag());
            } catch (IllegalArgumentException e) {
            }
        }
    
    public static String calendarToDate(Context context, Calendar calendar, String dateFormat) {
            if (calendar == null) {
                return null;
            }
    
            Locale locale = context.getResources().getConfiguration().locale;
            DateFormat df = new SimpleDateFormat(dateFormat, locale);
            TimeZone timeZone = TimeZone.getTimeZone("UTC");
            df.setTimeZone(timeZone);
    
            Date d = calendar.getTime();
            return df.format(d);
        }
    

    So, the core solver was to create Calendar with UTC timezone (because it works only with UTC values, and in formatted also I had to init UTC timezone, in other case it was shifting values for some hours depending on time zone.

    Also these two links helped to understand: https://github.com/material-components/material-components-android/blob/00dc4c6b5af3939418f1c7d1e4c737dc3fb7fd67/docs/components/Picker.md#timezones

    https://github.com/material-components/material-components-android/tree/master/catalog/java/io/material/catalog/datepicker

    And converter: https://www.epochconverter.com/