在另一种语言中使用 dateFormatter

Using dateFormatter in another language

我正在 运行ning 一段代码 returns nil 当 运行ning 在具有不同语言设置的 iPhone 上时。代码示例如下所示:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d, yyyy, h:mm a"

let thisDate = "Mar 4, 2017, 7:50 PM"
let foundationDate = dateFormatter.string(from: Foundation.Date())


print("As String - thisDate: \(thisDate), foundationDate: \(foundationDate)")    
print("As Date - thisDate: \(dateFormatter.date(from: thisDate)), foundationDate: \(dateFormatter.date(from: foundationDate))")

如果我 运行 这个,我得到:

As String - thisDate: Mar 4, 2017, 7:50 PM, foundationDate: okt. 22, 2017, 7:57 PM
As Date - thisDate: nil, foundationDate: Optional(2017-10-22 17:57:00 +0000)

谁能展示如何覆盖客户端设置,这样 thisDate 就不会 return 为零?

当您需要解析总是以固定语言到达的固定格式 date/time 字符串时,您需要设置日期格式化程序的区域设置,使其与您正在解析的数据相匹配。

在这种情况下,最好使用en_US_POSIX 的特殊语言环境。这确保无论用户的区域设置如何处理英文月份名称,以及正确处理设备上的 12/24 时间设置。

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