gpt4 book ai didi

iOS - NSDate 不正确地添加/减去时区差异

转载 作者:行者123 更新时间:2023-11-28 21:41:00 25 4
gpt4 key购买 nike

我正在尝试将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com