Material Date Range Picker showing incorrect current date Android

Viewed 1321

The current date in the Material Date Range picker is showing as yesterday's date. I looked into source code for the Material Design Picker and it seems to change the date while getting the date for the UTC timezone. The current date is the one which is encircled in the calendar. Is there any way to resolve the issue? The date range picker should show the correct date despite of the timezones.

One solution for the problem would be to change the current date manually, and I tried looking in the source code for the Datepicker but dont seem to find a method for this. Can the current date of Material Date Range picker be changed?

I am initialising the date picker as:

MaterialDatePicker.Builder builder = MaterialDatePicker.Builder.dateRangePicker();
final MaterialDatePicker materialDatePicker = builder.build();
materialDatePicker.show(fragmentManager, materialDatePicker.toString());

Kindly help.

4 Answers

I have updated the library to: material:1.3.0-alpha02 and it helped me.

I'm also faced with the same issue. I have made some searches but looks like there is an issue in the material library. I have fond some code and fixed the issue:

        CalendarConstraints.Builder calendarConstraintBuilder = new CalendarConstraints.Builder();
        calendarConstraintBuilder.setValidator(DateValidatorPointBackward.now());

        dateBuilder = MaterialDatePicker.Builder.dateRangePicker();
        dateBuilder.setTitleText("Select Date Range");
        dateBuilder.setCalendarConstraints(calendarConstraintBuilder.build());
        MaterialDatePicker<Pair<Long, Long>> picker = dateBuilder.build();
        picker.setMenuVisibility(false);
        picker.setAllowEnterTransitionOverlap(false);
        picker.show(getActivity().getSupportFragmentManager(), picker.toString());

        picker.addOnPositiveButtonClickListener(selection -> {

            Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            utc.setTimeInMillis(selection.first);
            String startDate = calendarToDate(getActivity(), utc, "dd-MMM-yyyy");
            utc.setTimeInMillis(selection.second);
            String endDate = calendarToDate(getActivity(), utc, "dd-MMM-yyyy");

            date.setText(startDate+" to "+endDate);

        });

And here is calendarToDate method:

public 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);
}
Related