【问题标题】:NSDateComponents possible timezone bug?NSDateComponents 可能的时区错误?
【发布时间】:2013-06-19 01:50:51
【问题描述】:

想知道我是否发现了 NSDateComponents 的错误。

使用 NSDateComponents 计算日期并在时区之间切换时,可能会在模拟器上得到错误的日期(未在设备上测试)。

它似乎是正确的偏移量,但方向错误。要么,要么我从根本上误解了某些东西(这总是一种明显的可能性)。

示例:

将系统时间设置为 UTC 以外的时区(我的是墨西哥,UTC-05:00)

// Get the components for the current absolute time.
NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSMinuteCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]];

// Get the calendar, which seems to set the time zone to the current time zone
components.calendar = [NSCalendar currentCalendar];
// Set the time zone to UTC
components.calendar.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

// Log the date
NSLog(@"Date at time zone: %@ : %@", components.calendar.timeZone, [components date]);
// Outputs (e.g): "Date at time zone: GMT (GMT) offset 0 : 2013-06-21 14:55:56 +0000"
// This should be absolute time, so any changes in the time zone should offset
// relative to this.

// Set the time zone to the local time zone (e.g. Mexico, 5 hours behind)
components.calendar.timeZone = [NSTimeZone localTimeZone];
// Log the date
NSLog(@"Date at time zone: %@ : %@", components.calendar.timeZone, [components date]);
// Outputs (e.g.): "Date at time zone: Local Time Zone (America/Mexico_City (CDT) offset -18000 (Daylight)) :2013-06-21 19:55:56 +0000"

假设墨西哥,第二个日期不应该比第一个晚五个小时吗?

【问题讨论】:

    标签: objective-c nsdatecomponents nstimezone


    【解决方案1】:

    components.calendar.timeZone 设置为墨西哥时区后,components 代表(在你的例子中)

    2013-06-21 14:55:56 in the Mexican time zone
    

    因此,[components date] 在该时间点返回 NSDate

    NSLog 输出使用NSDatedescription 方法,并将点打印在 时间始终采用 GMT 时区,即

    2013-06-21 19:55:56 +0000
    

    所以我觉得一切正常。

    【讨论】:

    • 明白。假设传递给组件的日期是不可变的,但 [components date]; 实际上返回一个 new 绝对时间点,具体取决于时区。现在有道理了。非常感谢。
    • @SimonFairbairn:不客气。 (时区和日历相关的计算可能会令人困惑!)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多