Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable past dates in Android date picker?

Tags:

android

How can I disable past dates in my Android date picker?

Here's the code that produces my DatePicker:

@Override protected Dialog onCreateDialog(int id) {     switch (id) {     case DATE_DIALOG_ID:         // set date picker as current date         return new DatePickerDialog(this, datePickerListener, year, month,                 day);     }     return null; }  private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {     public void onDateSet(DatePicker view, int selectedYear,             int selectedMonth, int selectedDay) {         year = selectedYear;         month = selectedMonth+1;         day = selectedDay;          startdate.setText(new StringBuilder().append(day).append("-")                 .append(getMonth(month + 1)).append("-").append(year)                 .append(" "));     } }; 
like image 420
Addy Avatar asked May 20 '14 14:05

Addy


People also ask

How do I turn off past date on android?

The Android DatePicker allows you to prevent dates in the past from being selected by using the setMinDate(long minDate) method.

How do I turn off past DatePicker?

the previous dates we need to set the minDate property of the date picker. if we set minDate:0 then it will disable all the previous dates. and we set input attribute min:current_date then it will disable all the previous dates.

How do I show only future dates in DatePicker?

To make any past dates disable or for only future dates, you first have to find the instantiation of the datepicker, and set the startDate setting to '+0d'.


2 Answers

You can do

datePicker.setMinDate(System.currentTimeMillis() - 1000); 

which sets today's date as minimum date and all the past dates are disabled.

datePicker is an object of DatePicker if you are using an object of DatePickerDialog you can do

datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000); 

Note: setMinDate was introduced in API 11

like image 111
Apoorv Avatar answered Sep 20 '22 08:09

Apoorv


This method will work properly.

//Get yesterday's date Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, -1);  //Set yesterday time milliseconds as date pickers minimum date DatePickerDialog datePickerDialog = new DatePickerDialog(context, myDateListener, year, month, day); datePickerDialog.getDatePicker().setMinDate(calendar.getTimeInMillis()); datePickerDialog.show(); 
like image 32
Arvin Jayanake Avatar answered Sep 20 '22 08:09

Arvin Jayanake