问题
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.
回答1:
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
回答2:
Your date format string is wrong. Change it to the following:
dateFormatter.dateFormat = "dd MMM yyyy"
For more information read Date Formatters documentation.
来源:https://stackoverflow.com/questions/32631435/datefromstring-returns-incorrect-date