SmartTree SmartTree - 1 month ago 17
iOS Question

UIDatePicker returns wrong date (-1 day to the real date)

I have a

UIDatePicker
mm/dd/yy. It works fine, but there is one problem: I set
minimum
and
maximum
date to it, and when user tries to choose the forbidden day, month or year, the
[datePicker date]
property begins working wrong. It returns you the
current day - 1
or
current month - 1
or
current year - 1
. I added some pictures, so you can see the situation.

Correct date This is correct

wrong date This is wrong (After choosing the forbidden date)

Does somebody know, how can I fix this ? Thanks !

UPD:
Code

[self.myDatePicker setMinimumDate:[NSDate date]];
[self.myDatePicker setMaximumDate:[[NSDate date] addTimeInterval:2 * 365.25 * 24 * 60 * 60]]; // to get upto 5 years
NSDate * now = [[NSDate alloc] init];
[self.myDatePicker setDate: now animated: YES];

self.myDatePicker.timeZone = [NSTimeZone localTimeZone];
self.myDatePicker.calendar = [NSCalendar currentCalendar];

Answer

It is deffinately something with the timezones and/or Daylight Saving Times. But it must be very subtle, as the code looks fine (beside the interval). Now to my question about if you are in russia:

This year the Kremlin did several back and forth swings on keeping daylight saving times forever. Actually I am not sure, what they decided at last. But maybe it isnt reflected correctly in Cocoa. The the video WWDC 2011 Video "Session 117 - Performing Calendar Calculations" , the presenter even mentions that things like that can happen.

Please try to work with dates with manually set times to noon, as this would keep you out of such mess.


The world just saw a similar misbehavior in iOS 6: the DND-Always-Active bug. I bet this was for a wrong date format (YYYY instead of yyyy)


Also try to set the timezone property on the picker at the very first thing and assign a manually instantiated Gregorian calendar to it.