dateFormatter 在瑞典返回 NSDate 为 nil



当此代码在瑞典运行时,我在转换 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;
}

NSDateFormatter使用当前区域设置。如果要识别美国格式的日期,请将格式化程序的区域设置设置为美国区域设置。

最新更新