Date Formatting Returns Nil [duplicate]

半腔热情 提交于 2021-02-05 12:28:59

问题


I'm getting nil when trying to create a date from a string. What am I doing wrong?

let createdAt = passesDictionary["createdAt"] as? String
print(createdAt)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let createdDate = dateFormatter.dateFromString(createdAt!)
print(createdDate)

createdAt is Optional("2016-05-03T19:17:00.434Z"), but createdDate is nil.


回答1:


The date string "2016-05-03T19:17:00.434Z" does match the pattern you gate to NSDateFormatter ("yyyy-MM-dd"). Try this pattern: yyyy-MM-dd'T'HH:mm:ss.SSSZ.

Here's a table of the tokens you can use in the dateFormat, as linked from the Apple documentation.



来源:https://stackoverflow.com/questions/37122158/date-formatting-returns-nil

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