Search code examples
androidandroid-calendarandroid-datepicker

getDatePicker().setMinDate of DatePickerDialog does not work


I want the DatePickerDialog to not show dates before current date. I'm using the setMinDate(long l) method. But it's not working.

I use a inner class where I set the minDate:

public static class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {
    DatePickerDialog datePickerDialog;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        String s = month + day + year+"";
        datePickerDialog = new DatePickerDialog(getActivity(),this,year,month,day);
        datePickerDialog.getDatePicker().setMinDate(Long.parseLong(s));

        // Create a new instance of DatePickerDialog and return it
            return  datePickerDialog;
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        SelectedDateView.setText(day+ (month + 1) + "-"  + "-" + year);

    }
}

This is the method that shows it:

public void showDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}

Solution

  • setMinDate() expects the unix time (milliseconds since January 1, 1970 00:00:00). Try something like this:

    long currentTime = new Date().getTime();
    datePickerDialog.getDatePicker().setMinDate(currentTime);
    

    Hope this helps.