简体   繁体   中英

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.

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)

Better Swift 3/3.1 solution:

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

try this code

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

//Monday, April 3, 2017...

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)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM