在瑞典运行此代码时,我在转换UTC时区的日期时间方面遇到了一个奇怪的问题。
NSString* utcDateTime = @"5/23/2017 4:34 AM";
NSString* localTimeNSString = [self convertUTCDateTimeToLocal:utcDateTime];
NSLog(@"localTime:%@", localTimeNSString);
在我的转换函数中,我尝试将此日期时间解析为NSDate会返回nil:
- (NSString*)convertUTCDateTimeToLocal:(NSString*)theUTCDateTime
{
NSString* localTime = nil;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
if (dateFormatter) {
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
// parse the passed parameter, theUTCDateTime, which looks like this: "05/23/2017 04:34 AM"
// Even though this date / time doesn't LOOK like a UTC-formatted timestamp, it is in the UTC timezone
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSDate* utcTime = [dateFormatter dateFromString:theUTCDateTime];
// in Sweden, dateFormatter will return utcTime as nil. Not so in the United States or England.
// In the US, NSLog of utcTime is "2017-05-23 04:34:00 +0000"
// Now that we've parsed into an NSDate, display date & time the way the user's system is configured
// Of course, if utcTime is nil, then so is localTime (below)
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatter.dateStyle = NSDateFormatterShortStyle;
dateFormatter.timeStyle = NSDateFormatterShortStyle;
localTime = [dateFormatter stringFromDate:utcTime];
// in the US, dateFormatter will return localTime as "5/22/17, 9:34 PM"
}
return localTime;
}
答案 0 :(得分:1)
NSDateFormatter
使用当前的区域设置。如果要以美国格式识别日期,请将格式化程序的区域设置设置为美国区域设置。