问题
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