简体   繁体   English

从NSDateComponents创建的NSDate不正确?

[英]NSDate created from NSDateComponents incorrect?

I created an NSDate by dateFromComponents , using NSCalendar with NSGregorianCalendar identifier, here's the strange part: The date get incorrect if it's before a certain point in time before 1900/12/31 我创建了一个NSDate通过dateFromComponents ,使用NSCalendarNSGregorianCalendar标识,这里的怪部分:日期不正确得到,如果是某一个点之前的时间1900年12月31日之前

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.year = 1900; components.month = 12; components.day = 31;
NSDate *date = [calendar dateFromComponents:components];

components.year = 1901; components.month = 1; components.day = 1;
NSDate *date2 = [calendar dateFromComponents:components];

NSLog(@"%@",calendar.timeZone.description); 
NSLog(@"%@",date);
NSLog(@"%@",date2);

The log will be: 日志将是:

2016-05-25 14:58:21.014 date[79754:2192157] Asia/Shanghai (GMT+8) offset 28800
2016-05-25 14:58:21.015 date[79754:2192157] 1900-12-30 15:54:17 +0000
2016-05-25 14:58:21.015 date[79754:2192157] 1900-12-31 16:00:00 +0000

As you can see, there is a 5 minutes gap during the day. 如您所见,白天有5分钟的差距。 However, if I set the timeZone by [NSTimeZone timeZoneForSecondsFromGMT:] , even with the same seconds deviation - 28800, it will be normal. 但是,如果我通过[NSTimeZone timeZoneForSecondsFromGMT:]设置timeZone,即使具有相同的秒偏差 - 28800,也是正常的。 What is the cause of this? 这是什么原因?

Interesting question. 有趣的问题。 What you are seeing is the effects of a time zone change from Local Mean Time to China Standard Time on 01-01-1901 when the clocks were turned back 05m43s. 您所看到的是当时钟转回05m43s时,从01-01-1901的本地平均时间到中国标准时间的时区变化的影响。

More details here . 更多细节在这里

No, the date isn't incorrect. 不,日期不正确。 Instead, the NSCalendar code knows things about calendars that you wouldn't dream about, like calendars changing their time offsets at some points in time in the past. 相反,NSCalendar代码知道您不会想到的有关日历的事情,例如日历在过去的某些时间点更改其时间偏移。

You asked for the Asia/Shanghai calendar to convert two dates, one on the day before they changed their time zone, one on the day after they changed their time zone, and both times are converted correctly. 您要求亚洲/上海日历转换两个日期,一个在他们更改时区的前一天,一个在他们更改时区的第二天,并且两个时间都正确转换。 That night everyone in Shanghai had to adjust their watches. 那天晚上,上海的每个人都要调整手表。

Try this!! 尝试这个!!

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *components = [[NSDateComponents alloc] init];

[components setYear:1987];
[components setMonth:3];
[components setDay:17];
[components setHour:14];
[components setMinute:20];
[components setSecond:0];

NSDate *date = [calendar dateFromComponents:components];

Hope this Help:) 希望这个帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM