77

How to Disable future dates in Android date picker

Java Code :

mExpireDate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                // To show current date in the datepicker
                final Calendar mcurrentDate = Calendar.getInstance();
                int mYear = mcurrentDate.get(Calendar.YEAR);
                int mMonth = mcurrentDate.get(Calendar.MONTH);
                int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);

                 DatePickerDialog mDatePicker = new DatePickerDialog(
                        EventRegisterActivity.this, new OnDateSetListener() {
                            public void onDateSet(DatePicker datepicker,
                                    int selectedyear, int selectedmonth,
                                    int selectedday) {

                                mcurrentDate.set(Calendar.YEAR, selectedyear);
                                mcurrentDate.set(Calendar.MONTH, selectedmonth);
                                mcurrentDate.set(Calendar.DAY_OF_MONTH,
                                        selectedday);
                                SimpleDateFormat sdf = new SimpleDateFormat(
                                        getResources().getString(
                                                R.string.date_card_formate),
                                        Locale.US);

                                mExpireDate.setText(sdf.format(mcurrentDate
                                        .getTime()));
                            }
                        }, mYear, mMonth, mDay);

                mDatePicker.setTitle(getResources().getString(
                        R.string.alert_date_select));
                mDatePicker.show();
            }
        });

How to do it?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
venu
  • 2,971
  • 6
  • 40
  • 59

12 Answers12

220

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.

jeet.chanchawat
  • 5,842
  • 5
  • 38
  • 59
laalto
  • 150,114
  • 66
  • 286
  • 303
  • where to add these lines ondatesetListner ?? – Saad Bilal May 15 '14 at 11:21
  • 1
    @SaadBilal, add these lines to the `onCreateDialog(int id){...}` after your dialog id case. – Dut A. Jul 02 '14 at 12:15
  • This solution may not work in some devices(future days of current month will be displayed). check my answer – Manikanta Jan 02 '17 at 11:42
  • this answer is working good.disabled future date.But still it is clickable and select that date – Stephen Jan 04 '17 at 05:44
  • It also disabled current date along with the future dates. I didn't want to disable the current date – Narendra Singh Jan 18 '17 at 05:56
  • I am using this https://github.com/wdullaer/MaterialDateTimePicker how can i disable future date? – Aditya Vyas-Lakhan Jul 11 '17 at 06:42
  • @AdityaVyas-Lakhan That library's `DatePickerDialog` has e.g. `setMaxDate(Calendar)`. Post a new question if you need help with that. – laalto Jul 11 '17 at 07:01
  • how to implement this in DialogFragment implements DatePickerDialog.OnDateSetListener – Amit Verma Sep 16 '17 at 06:55
  • Thanks I have implemented this in onCreateDialog // Create a new instance of DatePickerDialog and return it DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day); datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis()); return datePickerDialog; – Amit Verma Sep 16 '17 at 07:08
19

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!!!

Ravi
  • 34,851
  • 21
  • 122
  • 183
Satyaki Mukherjee
  • 2,857
  • 1
  • 22
  • 26
  • 3
    +1 for this. Instead of `.setMaxDate(new Date())`, it is better to instead use `.setMaxDate(System.currentTimeMillis())` since the expected argument is a `long`. Otherwise, your approach here is elegant and simple. – Dut A. Jul 02 '14 at 12:19
  • 1
    There is a bug in v5.0. setMaxDate() will grayed out date but still it can be selected. – Ketan Ahir Oct 17 '16 at 11:59
  • @KetanAhir Ya i am also facing the same issue. Were you able to resolve it? – Rahul Hawge Apr 18 '17 at 09:24
13

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();
Yashoda Bane
  • 399
  • 4
  • 7
6
 // Custom Your Future Dates  

 // Example for today and next 3 days :- 3(NUMBER OF NEXT DAYS)*24*60*60*1000l

 // As 24 represents hrs in day

 // As 60 mins 60 secs and convert it to millisec

 //Inside Class which implements DatePickerDialog.OnDateSetListener
 private Calendar mCurrentDate;

 //Inside OnCreate Method
 mDateEditText.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {

   mCurrentDate = Calendar.getInstance();
   int year = mCurrentDate.get(Calendar.YEAR);
   int month = mCurrentDate.get(Calendar.MONTH);
   int day = mCurrentDate.get(Calendar.DAY_OF_MONTH);

   DatePickerDialog mDatePickerDialog = new DatePickerDialog(this, this, year, month, day);
   mDatePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() + 3 * 24 * 60 * 60 * 1000 l);
  }
 });


 @Override
 public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
  mDateEditText.setText(dayOfMonth + "/" + month + "/" + year);

 }
Badr At
  • 658
  • 7
  • 22
5

If user select future date then update datepicker to current date(today)

you can use following code to check selected is future date or not

final Calendar cal = Calendar.getInstance();
datePickerDob.init(currentYear, currentMonth, currentDay,
            new OnDateChangedListener() {

                @Override
                public void onDateChanged(DatePicker view, int year,
                        int monthOfYear, int dayOfMonth) {
                    Calendar selectedCal = Calendar.getInstance();
                    selectedCal.set(year, monthOfYear, dayOfMonth);

                    long selectedMilli = selectedCal.getTimeInMillis();

                    Date datePickerDate = new Date(selectedMilli);
                    if (datePickerDate.after(new Date())) {

                        datePickerDob.updateDate(cal.get(Calendar.YEAR),
                                cal.get(Calendar.MONTH),
                                cal.get(Calendar.DAY_OF_MONTH));

                    } else {


                    }

                }
            });

You can also use compareTo() method

datePickerDate.compareTo(new Date());

Compare the receiver to the specified Date to determine the relative ordering.

Parameters date a Date to compare against.

Returns an int < 0 if this Date is less than the specified Date, 0 if they are equal, and an int > 0 if this Date is greater.

Ketan Ahir
  • 6,678
  • 1
  • 23
  • 45
3

If you using material design Datepicker :

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(this,
            calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
    datePickerDialog.show(getFragmentManager(), "datepicker");
    datePickerDialog.setMaxDate(calendar);
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
3

In Kotlin

cvCalendar.maxDate = System.currentTimeMillis()

Marsad
  • 859
  • 1
  • 14
  • 35
2
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    DatePickerDialog dialog = new DatePickerDialog(getActivity(), ondateSet, year, month, day);
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, 1);
    Date newDate = c.getTime();
    dialog.getDatePicker().setMaxDate(newDate.getTime() - (newDate.getTime() % (24 * 60 * 60 * 1000)));
    return  dialog;
}
2
**new Way**

 ed_date.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Calendar mcurrentDate=Calendar.getInstance();
                year=mcurrentDate.get(Calendar.YEAR);
                month=mcurrentDate.get(Calendar.MONTH);
                day=mcurrentDate.get(Calendar.DAY_OF_MONTH);

                final DatePickerDialog   mDatePicker =new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener()
                {
                    @Override
                    public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday)
                    {
                              ed_date.setText(new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
                            int month_k=selectedmonth+1;

                    }
                },year, month, day);
                mDatePicker.setTitle("Please select date");
                // TODO Hide Future Date Here
                mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());

                // TODO Hide Past Date Here
                //  mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis());
                mDatePicker.show();
            }
        }); 
Keshav Gera
  • 10,807
  • 1
  • 75
  • 53
2

Set the maximum date till tomorrow The last digit 1 in the code represents the number of days you want to set it.

  pickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() + (1000 * 60 * 60 * 24 * 1));
Varun
  • 45
  • 6
2

In kotlin , we can also pass this in setMaxDate(Date().time-86400000)

For example

dpd.datePicker.setMaxDate(Date().time - 86400000)
dpd.show()

here I am using dpd as object of DatePickerDialog. And there are 86400000 milliseconds in a day so I am setting the max date to be allowed a day before the current date. This will disable the future dates in calender.

SKumar
  • 43
  • 7
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 04 '22 at 07:48
-1
binding.edDate.setOnClickListener {
        val c = Calendar.getInstance()
        val year = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH)
        val day = c.get(Calendar.DAY_OF_MONTH)
        val datePickerDialog = DatePickerDialog(
            this, { view, year, monthOfYear, dayOfMonth ->
                val dat = (dayOfMonth.toString() + "-" + (monthOfYear + 1) + "-" + year)

                binding.edDate.setText(dat)
            },
            year,
            month,
            day
        )
        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis())
        datePickerDialog.show()
    }
  • Could you explain your code? Just posting a code snippet and not explaining your code - or why your code is different/better to the other (accepted) solutions is never really a brilliant idea. – SimonC Jan 08 '23 at 18:33
  • Hi SimonC I've taken up an variables and explained with an method is a static method of the Signature class that returns an instance of the Signature class that implements the specified signature algorithm, i.e, getinstance(). Also I've used Calendar Instance to pull dates with year. For some of the Android SDK versions Parse is not allowed as the application crashes at run time (Personal experience) datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis()) datePickerDialog.show() This code will give you the exact aspect which is required. – Akshay Prakash Mar 08 '23 at 10:16
  • Update your answer with your explanation, don't post it in the comments – SimonC Mar 08 '23 at 13:19