Convert Optional string to date

WDFAN23 picture WDFAN23 · Jul 27, 2015 · Viewed 26.6k times · Source

I have this Optional(2015-07-27 19:29:50 +0000) as a string? and I want to convert it to a date (NSDate) but I can't figure it out I've been searching a lot for solutions but I am pretty new to coding so if anyone could help I would appreciate it.

This is what I am using to convert the string to a date currently.

note: dateString is Optional(2015-07-27 19:29:50 +0000)

dateFormatter = NSDateFormatter()
println(dateFormatter)
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)

I always get a nil value

Answer

MirekE picture MirekE · Jul 27, 2015

If you are getting nil from NSDateFormatter, you likely specified incorrect date format. Try this:

let strTime = "2015-07-27 19:29:50 +0000"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
formatter.dateFromString(strTime) // Returns "Jul 27, 2015, 12:29 PM" PST