DateFormatter。在iOS设置中设置了12小时日期样式时,iOS 13.4.1上的行为异常

时间:2020-08-01 12:45:06

标签: swift dateformatter ios13.4

我发现iOS 13.4.1上DateFormatter的某些奇怪行为,而iOS设置中设置了12小时日期样式,现在是PM。

class DateFormatterTest {
    
    static var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS Z"
        return formatter
    }()
    
    static let testDate = Date()
    
    static func printDateString() {
        
        print(dateFormatter.string(from: testDate))
    }
}

DateFormatterTest.printDateString() 
// prints 2020-08-01 15:32:58.765 +0300 when 24h date style set in the iOS 13.4.1 system
// prints 2020-08-01 3:32:58.765 +0300 when 12h date style set in the iOS 13.4.1 system (EXPECTED: same as when 24h date style set.)

请注意,在使用Playground进行测试时,无论在MacOS上设置哪种日期样式,操场上始终会打印“ 2020-08-01 15:32:58.765 +0300”,这是正确的。

问题是如何在iOS 13.4.1上设置12h时间样式的情况下,以“ yyyy-MM-dd HH:mm:ss.SSS Z”格式获取正确的格式化日期字符串

我未在其他iOS版本上进行过测试,因此请发表评论(如果您在其他iOS版本上看到(或未看到)相同的行为

1 个答案:

答案 0 :(得分:0)

问题已解决。需要设置区域设置。

formatter.locale = Locale(identifier: "en_US_POSIX")