Using dateFormatter in another language [duplicate]

最后都变了- 提交于 2019-12-11 06:54:31

问题


I'm running a piece of code that returns nil when running on an iPhone with a different language setting. An example in code looks like this:

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))")

If I run this, I get:

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)

Can anyone show how to override the client settings so thisDate won't return nil?


回答1:


When ever you need to parse fixed format date/time strings that always arrive in a fixed language, you need to set the locale of the date formatter so it matches the data you are parsing.

In this case, it is best to use the special locale of en_US_POSIX. This ensures the English month names are handled regardless of the user's locale as well as properly handling 12/24 time settings on the device.

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


来源:https://stackoverflow.com/questions/46877573/using-dateformatter-in-another-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!