How to set minimum DatePicker date to current date
Solution 1:
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)
.
Solution 2:
If you don't want to use a custom dialog. Use this single line code:
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
Solution 3:
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
Solution 4:
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();
Solution 5:
Adding this line to your DatePicker Fragment will set the minimum date as current date & disable the previous months.
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());