Disable future dates from DatePickerDialog in Android
As we already know DatePickerDialog will be used to allow user to select date. It is useful when user wants to select Date of Birth or Start Date or End Date etc.
Here is the small code snippet of creating DatePickerDialog.
1 2 3 4 5 6 7 |
Calendar calendar = Calendar.getInstance(); int mYear = calendar.get(Calendar.YEAR); int mMonth = calendar.get(Calendar.MONTH); int mDay = calendar.get(Calendar.DAY_OF_MONTH); DatePickerDialog dpDialog = new DatePickerDialog(this, myDateListener, mYear, mMonth, mDay); dpDialog.show(); |
and to listen date selection event here is the listener
1 2 3 4 5 6 |
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker arg0, int year, int monthOfYear, int dayOfMonth) { Log.e("onDateSet()", "arg0 = [" + arg0 + "], year = [" + year + "], monthOfYear = [" + monthOfYear + "], dayOfMonth = [" + dayOfMonth + "]"); } }; |
With the above code you can select date from past as well as from future also, but when it comes to the DOB(Date of Birth) you can’t allow user to select future date.
In solution to this problem DatePickerDialog has a method getDatePicker() through which we can get DatePicker obeject and with that we can use setMaxDate() which will not allow user to select the date beyond the given date.
1 |
dpDialog.getDatePicker().setMaxDate(calendar.getTimeInMillis()); |
Here we have taken current time, so user will not be allowed to select future dates.