macos - dateFormatter 在瑞典返回 nil 的 NSDate

标签 macos datetime cocoa nsdate

当此代码在瑞典运行时,我在转换 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 使用当前区域设置。如果您想识别美国格式的日期,请将格式化程序的区域设置设置为美国区域设置。

关于macos - dateFormatter 在瑞典返回 nil 的 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44126619/

相关文章:

cocoa - 如何在 cocoa 事件模型 NPAPI 插件中获取 NSView

objective-c - 为什么 -isMemberOfClass : not work here?

objective-c - 子类化 NSCollectionView 后的绘图问题

macos - NSLog 仅用于调试?或者无论如何都要捕获日志?

c++ - 是否有 Mac OS X 相当于 Windows 的命名管道

c# - 当时间具有时区信息时,将 XML 读入 Datatable 会给出不正确的 DateTime

python - 在 python 列表中保持日期顺序的同时插入缺失的日期

c# - 获取特定月份的第一个工作日

android - 如何在 MacOs Lion 上设置 cocos2dx for android?

cocoa - NSMenu 不开始跟踪