Binoy Babu Binoy Babu - 4 months ago 36
Android Question

setMinDate(...) for DatePicker doesn't work when invoked a second time

I'm in a particular situation in which I have to alter the min and max date of

according to the selected element of a
. Here's the chunk of code I'm using to switch min and max date.

private void switchCalculationMethod(int method) {
calculationMethod = method;
switch (method) {
case METHOD_1:
datePicker.setMinDate(new LocalDate().minusWeeks(42).getMillis());
datePicker.setMaxDate(new LocalDate().plusDays(1).getMillis() - 1);
case METHOD_2:
datePicker.setMinDate(new LocalDate().minusWeeks(2).getMillis()); // This don't work!!
datePicker.setMaxDate(new LocalDate().plusWeeks(40).getMillis()); // This works!!!
datePicker.init(today.getYear(), today.getMonthOfYear() - 1,
today.getDayOfMonth(), this);

So, the
would get set up correctly the first time, problem occurs when I attempt to change the min date again (changing max date works). It would remain at the value I had set first. I'm thinking this is a bug. Am I doing something wrong here? Is there a workaround for this?.

PS : I'm using Joda time api.


This happens because method setMinDate() has check

 if (mTempDate.get(Calendar.YEAR) == mMinDate.get(Calendar.YEAR)
                && mTempDate.get(Calendar.DAY_OF_YEAR) != mMinDate.get(Calendar.DAY_OF_YEAR){

Simple workaround is to set min date with different year at first, for example


mPicker.setMinDate(new LocalDate().minusWeeks(2)

It works for me.