Question

I have the following code. When I run it on my iOS 3.1.3 device (get over it!) it works as expected, but when I run it on the simulator (iOS 5 and 4.3) it is 1 minute and 15 seconds off (9:01:15). Is this because of my code, a bug in the simulator or a bug in iOS 4+?

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]];
components.hour = 9;
components.minute = 0;
NSDate *date = [calendar dateFromComponents:components]; // <-- date is off on simulator

Thanks for your help!

Était-ce utile?

La solution

I don't fully understand why this is the case, but this happens when you use dateFromComponents: to create dates from a very long time ago. Specifically, the cutoff seems to be December 1, 1847. Anything earlier than 12am on that day seems to end up being 1 minute 15 seconds off.

In your case this is happening because if you only set components.hour and components.minute, you're getting a date from January 1st, 1AD.

If you set the year, month, and date to something more recent, like this:

components.year = 2012;
components.month = 2;
components.day = 6;

Then you'll get the right output (what I got in iOS simulator):

2012-02-06 09:00:00 +0000
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top