4
DatePicker datepicker = (DatePicker) view.findViewById(R.id.ad_date_picker);
datepicker.setMinDate(Calendar.getInstance().getTimeInMillis());

It just doesn't work. It works only in the xml (android:minDate="mm/dd/yyyy"), but I need to set the minimum date dynamically to the current day. My minimum API is 11.

Dennis
  • 2,271
  • 6
  • 26
  • 42
  • Doesn't work? Does that mean it crashes? It silently fails (are you using `try/catch`?)? Or what? – Cat Mar 17 '13 at 19:44
  • No. It just don't limit the options. – Dennis Mar 17 '13 at 19:44
  • Uhm its strange behaviour, it should works. – Simon Dorociak Mar 17 '13 at 19:46
  • Possible duplicate of this: http://stackoverflow.com/questions/13661788/how-to-set-minimum-datepicker-date-to-current-date It seems that you could try subtracting a second before you set the date? – span Mar 17 '13 at 19:47
  • @span I remember that thread also, but in that situation it was crashing (not just refusing to work). – Cat Mar 17 '13 at 19:49
  • I saw that thread. In my case, it doesn't crash. Maybe because it in a custom dialog? – Dennis Mar 17 '13 at 19:53
  • What if you set it to a date in a different year (Use `calendar.add(Calendar.YEAR, -5)`)? I have a hunch there is a bug in `setMinDate()` (from looking at the source code). – Cat Mar 17 '13 at 19:54
  • `Calendar cal = Calendar.getInstance();` `cal.add(Calendar.YEAR, -5);` `datepicker.setMinDate(cal.getTimeInMillis());` doesn't work. – Dennis Mar 17 '13 at 20:04
  • Do you have any ideas? – Dennis Mar 18 '13 at 07:09

1 Answers1

2

P.S: Solution used to work before but might be outdated now.

Try something like this. If I understand correctly, you wish to set the minimum date of spinner to today's date. It works for me without giving any error:

    Calendar cal = Calendar.getInstance();
    cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
    long time = cal.getTimeInMillis();
    DatePicker datepicker = (DatePicker) findViewById(R.id.datePicker);
    datepicker.setMinDate(time);

In your xml I am supposing that you have something like this:

<DatePicker
    android:id="@+id/datePicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124