How to Disable future dates in Android date picker

AndroidDatepickerAndroid Datepicker

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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.

Solution 2 - Android

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

Solution 3 - Android

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();

Solution 4 - Android

 // 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);

 }

Solution 5 - Android

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.

Solution 6 - Android

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);

Solution 7 - Android

In Kotlin

cvCalendar.maxDate = System.currentTimeMillis()

Solution 8 - Android

@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;
}

Solution 9 - Android

**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();
            }
        }); 

Solution 10 - Android

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));
  

Solution 11 - Android

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvenuView Question on Stackoverflow
Solution 1 - AndroidlaaltoView Answer on Stackoverflow
Solution 2 - AndroidSatyaki MukherjeeView Answer on Stackoverflow
Solution 3 - AndroidYashoda BaneView Answer on Stackoverflow
Solution 4 - Androidsaurabh kumbharView Answer on Stackoverflow
Solution 5 - AndroidKetan AhirView Answer on Stackoverflow
Solution 6 - AndroidPhạm HùngView Answer on Stackoverflow
Solution 7 - AndroidUmida ReimbaevaView Answer on Stackoverflow
Solution 8 - AndroidArmando Esparza GarcíaView Answer on Stackoverflow
Solution 9 - AndroidKeshav GeraView Answer on Stackoverflow
Solution 10 - AndroidVarunView Answer on Stackoverflow
Solution 11 - Androidnew1oneView Answer on Stackoverflow