Goomey Goomey - 1 year ago 76
Swift Question

dateFromString gives nil, swift

I am trying to create a NSDate object from a String. I have hardcoded my string for you to see. When i am calling dateFromString on my string, the result will be nil, and i am getting an exception because of unwrapping a nil.
I have pasted my code below.

Any ideas how to do this the right way?

Thank you very much!

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm"

let timeToParse = "19/10/2016 16:10"

let date = dateFormatter.dateFromString(timeToParse)
//date = nil?

dateFormatter.dateFormat = "yyyy/MM/dd hh:mmZZZ"
let dateWithUTC = dateFormatter.stringFromDate(date!)

Answer Source

You've supplied hh for hours, but this expects a format with 1-12 hours (with at least 2 digits). Since you're using 24 hours format (16:..), you need to use specifier HH instead, e.g.:

dateFormatter.dateFormat = "dd/MM/yyyy HH:mm"


  • avoid using explicit unwrapping of optionals (!), use e.g. optional binding (if let ...) instead, and
  • consider migrating to Swift 3: it's now official.

E.g. (Swift 3)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm"

let timeToParse = "19/10/2016 16:10"

if let date = timeToParse) {
    print(date) // 2016-10-19 16:10:00 +0000
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download