Pramath Nath
Pramath Nath

Reputation: 51

Disable the future date selection in datepicker

This is my date picker dialog code. I want to disable the future date selection in my date picker dialog box.

Can anybody suggest how?

@Override
protected Dialog onCreateDialog(int id)
{
    // TODO Auto-generated method stub
    switch(id)
    {
        case 1:
            Calendar cal=Calendar.getInstance();
            Toast.makeText(DateActivity.this, "- onCreateDialog -", Toast.LENGTH_LONG).show();
            return new DatePickerDialog(this,myDateSetListener,cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_YEAR));

        default:
            return null;
    }
}

private DatePickerDialog.OnDateSetListener myDateSetListener = new DatePickerDialog.OnDateSetListener()
{
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
    {
        // TODO Auto-generated method stub
        String date = "Year: " + String.valueOf(year) + "\n"
                    + "Month: " + String.valueOf(monthOfYear+1) + "\n"
                    + "Day: " + String.valueOf(dayOfMonth);

        Toast.makeText(DateActivity.this, date,Toast.LENGTH_LONG).show();
    }
};

Upvotes: 2

Views: 1558

Answers (3)

user3464252
user3464252

Reputation: 37

yourdatepicker.getDatePicker().setMaxDate(System.currentTimeMillis());

Upvotes: -1

NAP-Developer
NAP-Developer

Reputation: 3796

Put on this method inside on onCreateDialog, solved this problem for future date must be not selection on date picker dailog,

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        DatePickerDialog mDatePickerDialog = new DatePickerDialog(this, mDateSetListener, intYear, intMonth, intDay);
        mDatePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis()); // Important as Future date not selection
        return mDatePickerDialog;
    }
    return null;
}

Upvotes: 1

Axarydax
Axarydax

Reputation: 16623

Set an OnDateChangedListener to your DateTimePicker, where in

onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)

check if the date is in your allowed range and if not, call view.updateDate with your maximum allowed date.

Upvotes: 1

Related Questions