使用NSCalendar时遇到问题获取日期组件

时间:2016-02-17 03:32:58

标签: ios nscalendar nsdatecomponents

所以我有一个NSCalendar并做一些测试:

首先,将系统时区更改为America/Los_Angeles (GMT-8),给出一个unix时间戳1455552000000,将其转换为NSDate:by

[NSDate dateWithTimeIntervalSince1970:1455552000000 / 1000];

返回2016-02-15 16:00:00 +0000

然后使用日历生成日期组件:

+(void)applyCalendarToCurrentTimeZone:(NSCalendar *)calendar {
    if (![calendar.timeZone isEqualToTimeZone:[NSTimeZone localTimeZone]]) {
        calendar.timeZone = [NSTimeZone localTimeZone];
    }
}

+ (NSDateComponents *)getDateComponentsFromDate:(NSDate *)date {
    NSDateComponents *components;
    static NSCalendar *ISO8601 = nil;
    static NSCalendarUnit unit;
    if (!ISO8601) {
        ISO8601 = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
        ISO8601.firstWeekday = 2; // Sunday = 1, Saturday = 7
        ISO8601.minimumDaysInFirstWeek = 7;
        unit = NSCalendarUnitYear|NSCalendarUnitYearForWeekOfYear|NSCalendarUnitQuarter|NSCalendarUnitWeekOfYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
    }

    [ChartModel applyCalendarToCurrentTimeZone:ISO8601];

    components = [ISO8601 components:unit fromDate:date];
    return components;
}

但是在调试时,我发现了问题,

首先,一切看起来都很正常,日期组件正确,GMT-8时区的Day值为15

(lldb) po ISO8601.timeZone
America/Los_Angeles (GMT-8) offset -28800

(lldb) po date
2016-01-18 16:00:00 +0000

(lldb) po ISO8601.timeZone
America/Los_Angeles (GMT-8) offset -28800

(lldb) po date
2016-02-15 16:00:00 +0000

(lldb) po [ISO8601 components:unit fromDate:date];
<NSDateComponents: 0x13e4ae530>
    Calendar Year: 2016
    Month: 2
    Leap month: no
    Day: 15
    Hour: 8
    Minute: 0
    Second: 0
    Quarter: 0
    Year for Week of Year: 2016
    Week of Year: 7

(lldb) 

如果不重新启动应用,请将系统时区更改为自动,因为我在北京,它是GMT + 8,并刷新数据,日期组件看起来也很好,Day值为16在上海时区。

(lldb) po ISO8601.timeZone
Local Time Zone (Asia/Shanghai (GMT+8) offset 28800)

(lldb) po date
2016-02-15 16:00:00 +0000

(lldb) po [ISO8601 components:unit fromDate:date];
<NSDateComponents: 0x13ec15150>
    Calendar Year: 2016
    Month: 2
    Leap month: no
    Day: 16
    Hour: 0
    Minute: 0
    Second: 0
    Quarter: 0
    Year for Week of Year: 2016
    Week of Year: 7

(lldb) 

再一次,在没有重新启动应用程序的情况下,将系统时区更改为GMT-8,现在发生了奇怪的事情,GMT-8时区的Day值为16,这是不正确的!我错过了什么?请帮忙!

(lldb) po ISO8601.timeZone
Local Time Zone (America/Los_Angeles (GMT-8) offset -28800)

(lldb) po date
2016-02-15 16:00:00 +0000

(lldb) po [ISO8601 components:unit fromDate:date];
<NSDateComponents: 0x13f888260>
    Calendar Year: 2016
    Month: 2
    Leap month: no
    Day: 16
    Hour: 0
    Minute: 0
    Second: 0
    Quarter: 0
    Year for Week of Year: 2016
    Week of Year: 7

(lldb) 

0 个答案:

没有答案