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.
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+
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With