Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting NSDateComponents results in incorrect NSDate

I'm trying to get an NSDate object that has 21:00 as the local time - don't care about what day. I'm scratching my head at this very strange result:

NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:21];
[components setMinute:0];
[components setSecond:0];

NSDate *date = [calendar dateFromComponents:components];
NSLog(@"%@", date);

The result is 0001-01-02 04:52:58 +0000

I have no idea why. The current time is 17:34 PST, but the result doesn't change with the local time.

If I adjust the setMinute and setSecond lines to

[components setMinute:7];
[components setSecond:2];

I get 0001-01-02 05:00:00 +0000, which is correct (21:00 PST).

like image 559
apb Avatar asked Dec 26 '22 13:12

apb


1 Answers

The problem is that railroad time wasn't implemented until November 18, 1883. You're neglecting to set a year so you're getting a date before that. Prior to the implementation of railroad time, the US time zones weren't exact hour differences from GMT. I'm not sure exactly what time zone Apple selects for you but whichever it was seems to have been adjusted by 7 minutes and 2 seconds upon the move to PST in 1883.

like image 187
Tommy Avatar answered Jan 09 '23 17:01

Tommy