Janice Zhan Janice Zhan - 6 months ago 12
Swift Question

How to convert a string to Date in Swift2 2.0

I am working on convert a date string to

NSDate
, but I keep getting
nil
:

let strDate = self.DateList[0] // "2015-10-06T15:42:34Z"
print(strDate)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
print (dateFormatter.dateFromString(strDate))


And the running result is:

2016-05-18T14:00:54.466Z
nil


I dont know why, any suggestions?

Answer

You got 2016-05-18T14:00:54.466Z in a print(strDate)
so, Your format should be yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
//---------------------------------2016-05-18 T 14:00:54.466 Z ----

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"  
print (dateFormatter.dateFromString(strDate))
Comments