1

我在 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 上设置哪种日期样式, Playground 总是打印正确的“2020-08-01 15:32:58.765 +0300”。

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

我没有在其他 iOS 版本上进行测试,所以如果您在其他 iOS 版本上看到(或没有看到)相同的行为,请发表评论

4

1 回答 1

1

问题已解决。需要设置语言环境。

formatter.locale = Locale(identifier: "en_US_POSIX")
于 2020-08-01T14:08:00.460 回答