Convert Optional string to date

26,846

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
Share:
26,846
WDFAN23
Author by

WDFAN23

Updated on November 26, 2020

Comments

  • WDFAN23
    WDFAN23 over 3 years

    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

  • Dean Kelly
    Dean Kelly over 7 years
    Might mention if it's for the Swift class Date to use DateFormatter instead.