How do you set min and max dates in an Android DatePicker?

denza picture denza · Dec 28, 2013 · Viewed 19.1k times · Source

I am using Android's default date picker and my min supported SDK is 10 and I want to set the min and the max dates of the date picker.

Here is what I have in my MainActivity class after the onCreate method:

private void registerButtonListeners() {
    Calendar.setOnClickListener(new View.OnClickListener() 
    {   
        @Override
        public void onClick(View v) {
            showDialog(DATE_PICKER_DIALOG);
        }
    });
}

@Override
protected Dialog onCreateDialog(int id)
{
    switch(id)
    {
    case DATE_PICKER_DIALOG: return showDatePicker();

    }
    return super.onCreateDialog(id);
}
private DatePickerDialog showDatePicker()
{
        DatePickerDialog datePicker= new DatePickerDialog(MainActivity.this,android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth,new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                mCalendar.set(Calendar.YEAR,year);
                mCalendar.set(Calendar.MONTH,monthOfYear);
                mCalendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);
                updateDateText();

            }
        },mCalendar.get(Calendar.YEAR),mCalendar.get(Calendar.MONTH),mCalendar.get(Calendar.DAY_OF_MONTH));


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        {
            long d=1356994800000L;
            //datePicker.getDatePicker().setMinDate(d);
            //datePicker.getDatePicker().setMaxDate(1546210800000L);

        }
        return datePicker;
}

Answer

SweetWisher ツ picture SweetWisher ツ · Dec 28, 2013

You can get the underlying DatePicker from a DatePickerDialog (by simply calling getDatePicker()) and set its bounds using:

Where the argument is the usual number of milliseconds since January 1, 1970 00:00:00 in the default time zone. You'll still have to calculate these values of course, but that should be trivial to do with the Calendar class: just pass current date and add or substract x years from that..