Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift NSDateFormatter not using correct locale and format

Tags:

This is my code:

let currentDate = NSDate()
let usDateFormat = NSDateFormatter()
usDateFormat.dateFormat = NSDateFormatter.dateFormatFromTemplate("d MMMM y", options: 0, locale: NSLocale(localeIdentifier: "en-US"))
cmt.date = usDateFormat.stringFromDate(currentDate)

I was expecting to get "15 October 2015", but I got "oktober 15, 2015". The month is in swedish locale.

What have I done wrong? Both locale and format are wrong.

like image 847
Lord Vermillion Avatar asked Oct 15 '15 09:10

Lord Vermillion


People also ask

What is Dateformatter locale?

dateFormat(fromTemplate:options:locale:)Returns a localized date format string representing the given date format components arranged appropriately for the specified locale. iOS 4.0+ iPadOS 4.0+ macOS 10.6+ Mac Catalyst 13.1+ tvOS 9.0+ watchOS 2.0+

What is en_US_POSIX locale?

In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences.

Is DateFormatter thread safe iOS?

Thread SafetyOn iOS 7 and later NSDateFormatter is thread safe. In macOS 10.9 and later NSDateFormatter is thread safe so long as you are using the modern behavior in a 64-bit app.


2 Answers

Try this:

let dateString = "2015-10-15"
let formater = NSDateFormatter()
formater.dateFormat = "yyyy-MM-dd"
print(dateString)

formater.locale =  NSLocale(localeIdentifier: "en_US_POSIX")
let date = formater.dateFromString(dateString)
print(date)

Swift 3 Xcode 8

let dateString = "2015-10-15"
let formater = DateFormatter()
formater.dateFormat = "yyyy-MM-dd"
print(dateString)

formater.locale =  Locale(identifier: "en_US_POSIX")
let date = formater.date(from: dateString)
print(date!)

I hope it helps.

like image 62
ikbal Avatar answered Oct 13 '22 00:10

ikbal


Check out the documentation of dateFormatFromTemplate. It states that :

Return Value

A localized date format string representing the date format components given in template, arranged appropriately for the locale specified by locale.

The returned string may not contain exactly those components given in template, but may—for example—have locale-specific adjustments applied.

So thats the problem about arranging and language. To get the date you are looking for you need to set date formatter's dateFormat and locale as follow:

let currentDate = NSDate()
let usDateFormat = NSDateFormatter()
usDateFormat.dateFormat = "d MMMM y"
usDateFormat.locale = NSLocale(localeIdentifier: "en_US")
cmt.date = usDateFormat.stringFromDate(currentDate)
like image 44
Zell B. Avatar answered Oct 12 '22 23:10

Zell B.