我面临一个问题,它与不同的时区有关。
在UI中,我将日期设置为3/11/18
离开结束日期 -> 3/11/18
在服务中我得到结果。
离开结束日期 = "2018-03-11T06:00:00Z";
但是当我在UI中显示日期时,它显示"3/10/18",但实际结果应该是"3/11/18"
它在应用程序中显示的时间减少了 1 天。
我已更改时区是 ->华盛顿特区 - 美国,它应该适用于所有时区。
-
方法
调整日期。
NSDate* originalDateValue = [self valueForKey:actualKey]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z"; // tried formatter-> @"yyyy-MM-dd'T'HH:mm:ss'Z'"; // yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"]; NSString *dateString = [dateFormatter stringFromDate:originalDateValue]; dateFormatter.timeZone = [NSTimeZone localTimeZone]; NSDate * actualDate = [dateFormatter dateFromString:dateString]; [self setValue:actualDate forKey:actualKey];
-
我使用的另一种方法是:
调整日期。
NSDate* originalDateValue = [self valueForKey:actualKey];
NSDate* adjustedDateValue = [self.class adjustDate:originalDateValue forTimezone:[self timeZoneName]];
+(NSDate*)adjustDate:(NSDate*)originalDateValue forTimezone:(NSString*)timezoneName
{
if([originalDateValue isEqual:[NSNull null]]) return nil;
NSTimeInterval timeInterval = ([[NSTimeZone timeZoneWithName:timezoneName] secondsFromGMTForDate:originalDateValue] - [[NSTimeZone localTimeZone] secondsFromGMTForDate:originalDateValue]);
NSDate* adjustedDateValue = [originalDateValue initWithTimeInterval:timeInterval sinceDate:originalDateValue]; //[originalDateValue dateByAddingTimeInterval:timeInterval];
return adjustedDateValue;
}
第三种办法
NSDate* originalDateValue = [self valueForKey:actualKey]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ"; [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]]; NSString *dateString = [dateFormatter stringFromDate:originalDateValue]; NSDate* adjustedDateValue = [dateFormatter dateFromString:dateString];
有什么帮助吗?
originalDateValue
始终设置为您为其指定日期的 UTC 时间。 NSDate
适用于 UTC 时间,因为您没有指定时区。 dateFormatter
正在将您提供的输入转换为本地时间,这比当地时间晚了几个小时。由于您没有指定时间,因此它将时间设置为午夜 00:00:00,因此在将 UTC 转换为华盛顿特区时,您正在晚几个小时调整时区。
您必须根据从 UTC 到 localTimeZone
的偏移量调整源日期:
NSInteger sourceUTCOffset = [sourceTimeZone secondsFromGMTForDate:originalDateValue];
NSInteger destinationUTCOffset = [localTimeZone secondsFromGMTForDate:originalDateValue];
NSTimeInterval interval = destinationUTCOffset - sourceUTCOffset;
NSDate destinationDate = [initWithTimeInterval:interval sinceDate:originalDateValue];
然后按照您已经提供的方式进行操作destinationDate
。