Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dateFormatter in another language [duplicate]

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?

like image 644
Shane O'Seasnain Avatar asked Aug 27 '26 19:08

Shane O'Seasnain


1 Answers

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")
like image 183
rmaddy Avatar answered Aug 30 '26 09:08

rmaddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!