dateFromString() returns incorrect date

有些话、适合烂在心里 提交于 2020-01-21 14:39:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!