Setting NSDateComponents results in incorrect NSDate

ⅰ亾dé卋堺 提交于 2019-12-01 05:00:49

问题


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:


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.



来源:https://stackoverflow.com/questions/13596358/setting-nsdatecomponents-results-in-incorrect-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!