Skip to content Skip to sidebar Skip to footer

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

Solution 1:

Use:

   c1.setTimeZone(TimeZone.getTimeZone("UTC"));

instead of

   c1.setTimeZone(TimeZone.getDefault());

See if this helps or not:

Calendarc1= Calendar.getInstance(Locale.getDefault())

Solution 2:

I have solved this issue with such code:

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

            picker.addOnPositiveButtonClickListener(selection -> {
                Calendarutc= Calendar.getInstance(TimeZone.getTimeZone("UTC"));
                utc.setTimeInMillis(selection);
                Stringdate= ToolsManager.calendarToDate(this, utc, ToolsManager.LETY_FILTRATION_DATE_FORMAT);
                binding.textview.setText(date);
            });
            picker.show(getSupportFragmentManager(), picker.getTag());
        } catch (IllegalArgumentException e) {
        }
    }

publicstatic String calendarToDate(Context context, Calendar calendar, String dateFormat) {
        if (calendar == null) {
            returnnull;
        }

        Localelocale= context.getResources().getConfiguration().locale;
        DateFormatdf=newSimpleDateFormat(dateFormat, locale);
        TimeZonetimeZone= TimeZone.getTimeZone("UTC");
        df.setTimeZone(timeZone);

        Dated= 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/

Post a Comment for "Materialdatepicker Returns Incorrect Date After Selection"