由于某些未知原因,MaterialDatePicker 在选择后返回不正确的日期。例如,用户位于墨西哥地区,时区为:America/Tijuana。当他在视觉表示中选择:2021-10-05 时,在结果文本中我有 -1 天,2021-10-04。对于 RU 地区,一切正常。这是代码:
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());
}
当我设置时:.setSelection(MaterialDatePicker.todayInUtcMilliseconds())
它在日历上显示 10 月 18 日,但实际上今天是 10 月 20 日。