iPhone - NSDate格式:时间和时区的奇怪值



我测试了这些调用:

    NSLog(@"%@", [NSDate date]);
    NSLog(@"%@", [NSDate convertToUTC:[NSDate date]]);
    NSLog(@"%@", [[NSDate date] stringValueWithFormat:@"yyyyMMddHHmmss"]);
    NSLog(@"%@", [[NSDate convertToUTC:[NSDate date]] stringValueWithFormat:@"yyyyMMddHHmmss"]);
+ (NSDate*) convertToUTC:(NSDate*)sourceDate {
    [NSTimeZone resetSystemTimeZone];
    NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];
    NSTimeZone* utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval gmtInterval = gmtOffset - currentGMTOffset;
    NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:sourceDate] autorelease];     
    return destinationDate;
}
- (NSString*) stringValueWithFormat:(NSString*)formatRetour {
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:formatRetour];
    return [dateFormatter stringFromDate:self];
}

他们给了我:

2011-08-17 13:03:58 +0000
2011-08-17 11:03:58 +0000
20110817150358
20110817130358

在我的手机上,所有配置为法国/法语,现在是:15:03:58。

我不明白这里的转换。

1给出GMT的实时时间
给了我一些我不明白的东西…
3给出了电话上的实时时间
4给出GMT时间

我迷路了……2是从哪里来的?这些调用是如何工作的?
我的意思是,[NSDate date]给出的是13:03,时区是+0000。为什么要格式化显示15:03 ?
为什么1和2显示的是+0000时区,而时间不同?

你能告诉我怎么做吗?

NSLog将始终以+0000时区打印日期对象的描述。

当您使用NSDateFormatter从日期获取字符串时,它将使用您手机的时区。有了"yyyyMMddHHmmssZZZ",你会得到20110817150358+0200

对于转换为UTC的日期也是一样的:对于GMT+0 (NSLog),您得到11:03,这与13:03+0200(使用NSDateFormatter)相同。

然而convertToUTC:是错误的,因为值应该是13:03+0000。

NSDate到NSDate的转换方法没有意义。NSDate保存绝对时间,不关心时区。你只需要在做NSString from/to NSDate转换时考虑时区。

这就是为什么当你"convertToUTC" 15:03+0200时,你会得到13:03+0200,这和11:03+0000是一样的。

- (NSString *)UTCRepresentation这样的方法是有意义的。

不要被NSLog的输出弄糊涂了。NSLog还需要一个格式化程序来正确显示[NSDate date]。当你考虑到这一点时,它应该都是有意义的。

最新更新