【问题标题】:NSDate created from NSDateComponents incorrect?从 NSDateComponents 创建的 NSDate 不正确?
【发布时间】:2016-05-25 07:05:55
【问题描述】:

我通过dateFromComponents 创建了一个NSDate,使用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);

日志将是:

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

如您所见,白天有 5 分钟的间隔。 但是,如果我将 timeZone 设置为[NSTimeZone timeZoneForSecondsFromGMT:],即使秒偏差相同 - 28800,也将是正常的。 这是什么原因?

【问题讨论】:

    标签: ios nsdate nscalendar nsdatecomponents


    【解决方案1】:

    不,日期不正确。相反,NSCalendar 代码知道有关日历的事情,这是您做梦也想不到的,例如日历在过去的某个时间点更改了它们的时间偏移量。

    您要求亚洲/上海日历转换两个日期,一个在他们更改时区的前一天,一个在他们更改时区的第二天,并且两个时间都正确转换。那天晚上,上海的每个人都得调表。

    【讨论】:

    • 如果我将时区设置为亚洲/上海,我会得到完全相同的结果。不错的收获。
    【解决方案2】:

    有趣的问题。您看到的是时区从 1901 年 1 月 1 日从本地标准时间更改为中​​国标准时间的影响,当时时钟拨回 05 分 43 秒。

    更多详情here.

    【讨论】:

      【解决方案3】:

      试试这个!!

      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];
      

      希望得到帮助:)

      【讨论】:

      • 因为你的答案是无关紧要的。
      • 兄弟,我认为您的问题是从组件创建 NSdate 对吗?
      • 这不是我的问题。
      • 你能解决这个问题吗?你遇到了什么问题?
      • 这不是我的问题。问题是,我们一生中可能会面临一个有价值的 NSDate 问题。而且你的回答完全无关紧要。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 1970-01-01
      • 2012-04-23
      • 1970-01-01
      • 2013-04-17
      相关资源
      最近更新 更多