Setting NSDateComponents results in incorrect NSDa

2019-02-17 23:46发布

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).

1条回答
Animai°情兽
2楼-- · 2019-02-18 00:02

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.

查看更多
登录 后发表回答