【问题标题】:dateFormatter returns an NSDate of nil in SwedendateFormatter 在瑞典返回 nil 的 NSDate
【发布时间】:2017-05-23 05:39:29
【问题描述】:

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

【问题讨论】:

  • 谢谢。抱歉——习惯的力量(它所属的代码库是 Objective-C++,但我知道这个问题不是 C++ 语言问题)

标签: macos datetime cocoa nsdate


【解决方案1】:

NSDateFormatter 使用当前语言环境。如果您想识别美国格式的日期,请将格式化程序的语言环境设置为美国语言环境。

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 2023-03-14
    • 1970-01-01
    • 2015-07-09
    • 2020-04-10
    相关资源
    最近更新 更多