Convert String to NSDate with Swift 2

iOSGeek picture iOSGeek · Oct 10, 2015 · Viewed 17.2k times · Source

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

zaph picture zaph · Oct 10, 2015

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

Swift 3.0

let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:strDate)
print("date: \(date!)")

Output:

date: 2015-11-01 00:00:00 +0000

Swift 2.x

let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.dateFromString(strDate)
print("date: \(date!)")

Output:

date: 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.