iOSGeek iOSGeek - 1 month ago 9
iOS Question

Convert String to NSDate with Swift 2

I'm trying to convert a string to

NSDate
here is my code

let strDate = "2015-11-01T00:00:00Z" // "2015-10-06T15:42:34Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ssZ"
print ( dateFormatter.dateFromString( strDate ) )


I keep getting
nil
as a result

Answer

The "T" in the format string needs to be single quoted so it will not be consider a symbol:

let strDate = "2015-11-01T00:00:00Z" // "2015-10-06T15:42:34Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
print ( dateFormatter.dateFromString( strDate ) )

Optional(2015-11-01 00:00:00 +0000)

See: Date Field SymbolTable.

This includes the need to enclose ASCII letters in single quotes if they are intended to represent literal text.

Comments