问题
I'm using a DatePickerDialog to select a begin / end Date to search in an article list.
Thing is DatePickerDialog's setMinDate actually set also default position of dialog box when opened and block user from selecting an anterior date:
Here's my date gestion method:
private void createDisplay(DatePickerDialog.OnDateSetListener dateSetListener) {
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
DatePickerDialog dialog = new DatePickerDialog(
Objects.requireNonNull(getActivity()),
R.style.DatePickerDialogTheme,
dateSetListener,
day, month, year);
dialog.getDatePicker().setMaxDate(cal.getTimeInMillis());
cal.add(Calendar.YEAR, -5);
dialog.getDatePicker().setMinDate(cal.getTimeInMillis());
dialog.show();
}
I mean, it should be today as default position but if I use setMinDate I can't select an anterior position of today's date...
回答1:
Use it like this -
Example:
// Adding 3 days
calendar.add(Calendar.DATE, 3);
// Set the Calendar new date as maximum date of date picker
dpd.getDatePicker().setMaxDate(calendar.getTimeInMillis());
// Subtract 6 days from Calendar updated date
calendar.add(Calendar.DATE, -6);
// Subtract 6 months from Calendar updated date
calendar.add(Calendar.MONTH, -6);
Or you can use
dpd.getDatePicker().setMinDate(new Date().getTime());
Note - put any date as you wish and modify it like this:
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm");
formatter.setLenient(false);
Date curDate = new Date();
long curMillis = curDate.getTime();
String curTime = formatter.format(curDate);
String oldTime = "05.01.2011, 12:45";
Date oldDate = formatter.parse(oldTime);
long oldMillis = oldDate.getTime();
And then
dpd.getDatePicker().setMinDate(oldMillis);
来源:https://stackoverflow.com/questions/56750479/how-to-make-datepickerdialogs-setmindate-different-from-setcurrentdate