-2

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.

raginggoat
  • 3,570
  • 10
  • 48
  • 108

1 Answers1

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.

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • This answer simply states the obvious. It does not help the user solve the problem. – rmaddy May 09 '16 at 17:51
  • 2
    BTW - there was no need to post this answer since this question has been asked and answered hundreds of times before. Always look for duplicates before posting an answer. – rmaddy May 09 '16 at 17:54
  • I'll keep that in mind in the future – Alexander May 09 '16 at 18:01