Lord Vermillion
Lord Vermillion

Reputation: 5424

Swift NSDateFormatter not using correct locale and format

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.

Upvotes: 22

Views: 46388

Answers (6)

Selçuk Aslantaş
Selçuk Aslantaş

Reputation: 39

Date Locale:

dateFormatter.locale = Locale(identifier: Locale.preferredLanguages.first ?? "en")

Upvotes: -1

DàChún
DàChún

Reputation: 5146

You can use the Date extension in Swift5:

extension Date {
    var timestamp: String {
        let dataFormatter = DateFormatter()
        dataFormatter.locale = Locale(identifier: "en_US_POSIX")
        dataFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS"
        return String(format: "%@", dataFormatter.string(from: self))
    }
}

You can get the timestamp by

print("Now: \(Date().timestamp)")

Upvotes: 1

ikbal
ikbal

Reputation: 1174

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.

Upvotes: 34

szubiszon
szubiszon

Reputation: 106

Better Swift 3/3.1 solution:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")

Upvotes: 6

mahdiTGK
mahdiTGK

Reputation: 53

try this code

let locale1:Locale = NSLocale(localeIdentifier: "en_US") as Locale
var date =  Date().description(with: locale1)
print(date)

//Monday, April 3, 2017...

Upvotes: 3

Zell B.
Zell B.

Reputation: 10286

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)

Upvotes: 16

Related Questions