当我创建MaterialDatePicker
它时,它会选择我指定的日期的前一个日期,而不是指定的日期:
您可以看到 EditText 有 May 12, 2019 但 DatePicker 显示为 May 11, 2019
openDatePicker 的代码是:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
String dateText = "May 12, 2019";
binding.etDate.setText(dateText);
try {
Date date = new SimpleDateFormat("MMM dd, yyyy").parse(dateText);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
binding.etDate.setTag(cal);
} catch (ParseException e) {
e.printStackTrace();
}
binding.etDate.setOnClickListener(v -> {
Calendar defaultCal = Calendar.getInstance();
if (binding.etDate.getTag() != null) {
defaultCal = (Calendar) binding.etDate.getTag();
}
openDatePicker(binding.etDate, defaultCal, createDatePickerConstraints(defaultCal, null, null));
});
}
private void openDatePicker(final EditText tv, Calendar defaultDate, CalendarConstraints constraints) {
try {
MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();
builder.setCalendarConstraints(constraints);
builder.setSelection(defaultDate.getTimeInMillis());
MaterialDatePicker<Long> datePicker = builder.build();
datePicker.addOnPositiveButtonClickListener(selection -> {
Calendar selectedCalObj = Calendar.getInstance();
selectedCalObj.setTimeInMillis((long) selection);
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH);
dateFormat.setTimeZone(TimeZone.getDefault());
String date = dateFormat.format(selectedCalObj.getTime())
.replace("a.m.", "AM")
.replace("p.m.", "PM")
.replace("am", "AM")
.replace("pm", "PM");;
tv.setText(date);
tv.setTag(selectedCalObj);
});
datePicker.addOnNegativeButtonClickListener(view -> {
Log.d(TAG, "Cancelled");
});
datePicker.show(getSupportFragmentManager(), TAG);
} catch (Exception e) {
e.printStackTrace();
}
}
// helper function to give the constraints:
private CalendarConstraints createDatePickerConstraints(final Calendar entry, final Calendar start, final Calendar end) {
CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
if (entry != null)
constraintsBuilder.setOpenAt(entry.getTimeInMillis());
if (start != null) {
constraintsBuilder.setStart(start.getTimeInMillis());
constraintsBuilder.setValidator(DateValidatorPointForward.from(start.getTimeInMillis()));
}
if (end != null) {
constraintsBuilder.setEnd(end.getTimeInMillis());
constraintsBuilder.setValidator(DateValidatorPointBackward.before(end.getTimeInMillis()));
}
return constraintsBuilder.build();
}
我知道的可能方法是通过将EditText
binding.etDate.setTag
at偏移onCreate
到我所在的当前时区来修复(因为问题是 2019 年 5 月 12 日 0:00:00 这可能是 DatePicker 选择上一个日期的问题打开),但如果有更好的方法来做到这一点,这将非常有帮助,因为这似乎是一个更常见的代码,在任何地方都很有用,这样我就可以将它作为一个库并在我的主要应用。
任何帮助,将不胜感激。