简体   繁体   中英

dateFromString() returns incorrect date

I'm trying to convert string to Date, but it result incorrect date.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM YYYY"
let dt = dateFormatter.dateFromString("17 Sep 2015")
println("Date : \(dt)") 

It result

Date : Optional(2014-12-20 18:30:00 +0000)

Please let me know where I'm making mistake. I tried other format too, but it return nil.

The format for year is incorrect, it should be yyyy , not YYYY .

"Y": Year (in "Week of Year" based calendars). This year designation is used in ISO year-week calendar as defined by ISO 8601, but can be used in non-Gregorian based calendar systems where week date processing is desired. May not always be the same value as calendar year .

See: Date Field SymbolTable.
Also: ICU Formatting Dates and Times

Your date format string is wrong. Change it to the following:

dateFormatter.dateFormat = "dd MMM yyyy"

For more information read Date Formatters documentation.

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