venu
venu

Reputation: 2979

How to Disable future dates in Android date picker

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?

Upvotes: 78

Views: 86401

Answers (12)

Akshay Prakash
Akshay Prakash

Reputation: 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()
    }

Upvotes: -1

SKumar
SKumar

Reputation: 43

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.

Upvotes: 2

Umida Reimbaeva
Umida Reimbaeva

Reputation: 31

In Kotlin

cvCalendar.maxDate = System.currentTimeMillis()

Upvotes: 3

Varun
Varun

Reputation: 45

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

Upvotes: 2

Yashoda Bane
Yashoda Bane

Reputation: 399

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

Upvotes: 13

saurabh kumbhar
saurabh kumbhar

Reputation: 71

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

 }

Upvotes: 6

laalto
laalto

Reputation: 152787

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.

Upvotes: 223

Phạm Hùng
Phạm Hùng

Reputation: 25

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

Upvotes: 3

Keshav Gera
Keshav Gera

Reputation: 11244

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

Upvotes: 2

Satyaki Mukherjee
Satyaki Mukherjee

Reputation: 2879

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

Upvotes: 20

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

Upvotes: 2

Ketan Ahir
Ketan Ahir

Reputation: 6728

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.

Upvotes: 5

Related Questions