I want to set the minimum date the user can choose in a DatePicker to the current date. I\'ve tried this:
DatePicker datePicker = (DatePicker) findViewById(R
Try this
datePicker.setMinDate(new GregorianCalendar.getTimeInMillis());
The error says you cannot set the minimum date to exactly now. Try subtracting a second:
datePicker.setMinDate(System.currentTimeMillis() - 1000);
From the source code the minimum date must be before, not equal to, the current date:
if (date.before(mMinDate)) {
throw new IllegalArgumentException("fromDate: " + mMinDate.getTime()
+ " does not precede toDate: " + date.getTime());
}
So you simply need to subtract enough time from now (System.currentTimeMillis()
) pass date.before(mMinDate)
.
This can help you.
Calendar cal=Calendar.getInstance();
int year=cal.get(Calendar.YEAR);
int month=cal.get(Calendar.MONTH);
int day=cal.get(Calendar.DAY_OF_MONTH);
int hour=cal.get(Calendar.HOUR_OF_DAY);
int min=cal.get(Calendar.MINUTE);
datePicker.updateDate(year, month, day);
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(min);
Check the Android DatePickerDialog set minimum and maximum date code.
Here is the examples.
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(getActivity(),AlertDialog.THEME_TRADITIONAL,this,year, month, day);
//Get the DatePicker instance from DatePickerDialog
DatePicker dp = dpd.getDatePicker();
//Set the DatePicker minimum date selection to current date
dp.setMinDate(c.getTimeInMillis());//get the current day
//dp.setMinDate(System.currentTimeMillis() - 1000);// Alternate way to get the current day
//Add 6 days with current date
c.add(Calendar.DAY_OF_MONTH,6);
//Set the maximum date to select from DatePickerDialog
dp.setMaxDate(c.getTimeInMillis());
//Now DatePickerDialog have 7 days range to get selection any one from those dates
This worked perfectly for me. easy and nice.
DatePickerDialog dialog = new DatePickerDialog(this, this,
Calendar.YEAR,Calendar.MONTH,
Calendar.DAY_OF_MONTH);
dialog.getDatePicker().setMinDate(Calendar.getInstance().getTimeInMillis());
dialog.show();
datePicker.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
The minimum date can't be the instant moment