0

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!

jrtc27
  • 8,496
  • 3
  • 36
  • 68

1 Answers1

2

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
yuji
  • 16,695
  • 4
  • 63
  • 64
  • 1
    Could be because (according to Wikipedia) this was when companies switched over to a standard time in the UK (http://en.wikipedia.org/wiki/Railway_time#Great_Britain). – jrtc27 Feb 06 '12 at 16:40
  • Thanks for that—and for the historical tidbit :) – yuji Feb 06 '12 at 21:44
  • If you don't specify the time zone in the date components, the conversion is going to assume the current time zone. For historical dates, the time zone library will at some point assume actual local time (i.e. actual minutes and seconds east/west of the UTC line). Before 1847, London was 75 seconds west of the (current) GMT, so your values are being interpreted off of that. See http://stackoverflow.com/questions/21921589/where-is-the-extra-75-seconds-coming-from – Carl Lindberg Jun 01 '14 at 18:12