NSDate时区解释不正确

时间:2014-08-19 11:48:09

标签: ios objective-c nsdate nsdateformatter

当我有一个值为“17:00:00 +0000”的时间字符串时,它会被dateformatter转换为18:00:00 CET。但我希望在NSDate有17:00:00。

这是我在某个方法中用来返回NSDate对象的代码

NSString* time = @"17:00:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[dateFormatter setDateFormat:@"HH:mm:ss Z"];

NSDate* convertedDate = [dateFormatter dateFromString:time];

这是我需要将小时作为整数的部分

NSDateComponents *components = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:time];
[components setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSInteger hour = [components hour];

小时将是18而不是17。

1 个答案:

答案 0 :(得分:0)

问题在于使用日期的代码,而不是将字符串转换为日期的位置。您可以尝试设置calendar的时区而不是NSDateComponents来获得所需的行为:

[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
// and then do the rest
NSDateComponents *components = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:time];
NSInteger hour = [components hour];

NSDate不存储任何自定义时区(它将所有数据存储在同一" base"时区),您可以显示转换为指定时区的NSDate实例,但无法设置任何NSDate实例的任何时区。因此,只有当您将时区显示给用户时,时区才会跳转。此外,经验法则说:始终以UTC格式存储/传输数据。

NSDate *date = ...
date.timeZone = ... // No such thing
// this is how you can see which time is represented by NSDate in a specific time zone
// note there's no such function as StringFromNSDateWithTimeZone
NSLog("TimeZone: %@", StringFromNSDateWithTimeZone(date, SOME_TIME_ZONE)) 

这意味着你应该检查你的NSDate显示代码而不是你的字符串到NSDate代码(它似乎做你期望的那样)。

只需添加更多胶水:17:00:00 +0000 (GMT) = 18:00:00 +0100 (CET)