Syed e Hussaini Syed e Hussaini - 2 months ago 8
iOS Question

Swift - NSDateFormater is not working

I am calling an API to get some data. API response returns date and time in

String
format but when I parse it into
NSDate
using
DateFormatter
it shows
nil
instead of date.String formate that I get from API is
2016-10-09T12:15:17.000Z
.

Here is my code.

let dateString = dataDict.objectForKey("schedule_date") as! String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
print(dateFormatter.dateFromString(dateString))

Answer

change your date formatter like yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

let dateString = dataDict.objectForKey("schedule_date") as! String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
print(dateFormatter.dateFromString(dateString))

Note: SSS is here for milliseconds.

Comments