How to Disable future dates in Android date picker
Following code help you to disable future dates:
Declare calendar variable globally:
private Calendar myCalendar = Calendar.getInstance();
Put following code in onCreate method:
DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
On the button click put the following code:
DatePickerDialog datePickerDialog=new DatePickerDialog(getActivity(), dateListener, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH));
//following line to restrict future date selection
datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
datePickerDialog.show();
Get the DatePicker
from DatePickerDialog
with getDatePicker()
. Set the max date to current date with setMaxDate()
:
mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());
Requires API level 11.
You can call getDatePicker().setMaxDate(long) on your DatePickerDialog to set today as your maximum date. You can update the function with the same name from the snippet you posted.
Note:: DatePickerDialog is the object that I referenced in the Android Docs from the link I posted.
@Override
protected Dialog onCreateDialog(int id) {
Calendar c = Calendar.getInstance();
int cyear = c.get(Calendar.YEAR);
int cmonth = c.get(Calendar.MONTH);
int cday = c.get(Calendar.DAY_OF_MONTH);
switch (id) {
case DATE_DIALOG_ID:
//start changes...
DatePickerDialog dialog = new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
dialog.getDatePicker().setMaxDate(System.currentTimeMillis());
return dialog;
//end changes...
}
return null;
}
Try this and give your feedback!!!