问题
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