【发布时间】:2011-10-27 05:30:55
【问题描述】:
在解析不同时区的日期时,我注意到 NSDateFormatter 在处理很久以前的日期时会产生奇怪的结果。
我有以下代码:
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString* dateString1 = @"1890-09-30 12:00";
NSString* dateString2 = @"1890-10-01 12:00";
NSLog(@"original timezone %@", [dateFormatter timeZone]);
NSDate* localDate1 = [dateFormatter dateFromString:dateString1];
NSDate* localDate2 = [dateFormatter dateFromString:dateString2];
NSLog(@"localDate1 %@ » %@", dateString1, localDate1);
NSLog(@"localDate2 %@ » %@", dateString2, localDate2);
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate* utcDate1 = [dateFormatter dateFromString:dateString1];
NSDate* utcDate2 = [dateFormatter dateFromString:dateString2];
NSLog(@"utcDate1 %@ » %@", dateString1, utcDate1);
NSLog(@"utcDate2 %@ » %@", dateString2, utcDate2);
我希望 localDates 比 UTC 时间少一小时,因为我的时区是 CET。相反,我得到了这个:
original timezone Europe/Budapest (CEST) offset 7200 (Daylight)
localDate1 1890-09-30 12:00 » 1890-09-30 10:43:40 +0000
localDate2 1890-10-01 12:00 » 1890-10-01 11:00:00 +0000
utcDate1 1890-09-30 12:00 » 1890-09-30 12:00:00 +0000
utcDate2 1890-10-01 12:00 » 1890-10-01 12:00:00 +0000
经过一番调查,该错误似乎出现在早于 1890-09-30 23:43 的日期。
这是什么原因?这是 iOS 日期处理中的错误吗?
【问题讨论】: