我正在尝试将 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 - NSDate 不正确地添加/减去时区差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32068571/