我正在尝试将UTC格式的日期时间转换为其他时区

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"PKT"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *finalDate = [dateFormatter dateFromString:@"2015-08-18T23:00:00"];


PKT为UTC + 05:00,结果应为2015-08-19 04:00:00 +0000,而不是减法,结果为2015-08-18 18:00:00 +0000。

我做错了什么?

最佳答案

我仍然不知道是什么原因造成了错误的加/减时间。如果我通过UTC + 05:00作为时区缩写,那么它会减去;如果​​我通过UTC-05:00,则我会增加时间。我找到了解决方法并解决了这个问题,这里是代码

+(NSString*)getDBDate_UTC:(NSString*)date{

NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
[formatter1 setCalendar:[NSCalendar calendarWithIdentifier:NSCalendarIdentifierISO8601]];
[formatter1 setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[formatter1 setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSDate* sourceDate = [formatter1 dateFromString:date];

NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC+05:00"];
NSTimeZone* destinationTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];

return [formatter1 stringFromDate:destinationDate];

}


希望这可以帮助

关于ios - iOS-NSDate未添加/减去时区差异,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32068571/

10-15 15:16