dateFromString() returns incorrect date

2019-02-26 02:53发布

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.

2条回答
我命由我不由天
2楼-- · 2019-02-26 03:53

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

dateFormatter.dateFormat = "dd MMM yyyy"

For more information read Date Formatters documentation.

查看更多
手持菜刀,她持情操
3楼-- · 2019-02-26 03:55

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

查看更多
登录 后发表回答