-2

I am trying to convert a string to an NSDate. I found how to do it on a couple posts, but for some reason doesn't work.

     let dateFormatter = NSDateFormatter()
     dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
     var test = dictionary["time"] as! String
     loadedItem.time = dateFormatter.dateFromString(test)
     println("Time recorded as: \(loadedItem.time)")
     println("Time from server: " + test)

The console log is:

    Time recorded as: nil
    Time from server: 2015-07-07 21:46:11
    Time recorded as: nil
    Time from server: 2015-07-07 21:58:09
    Time recorded as: nil
    Time from server: 2015-07-07 22:02:35
    Time recorded as: nil
    Time from server: 2015-07-07 23:46:49

As you can see, the string is never formatted.

patrickd
  • 275
  • 3
  • 14

1 Answers1

0

HH is 24 hour format

 let dateFormatter = NSDateFormatter()
 dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
 var test = dictionary["time"] as! String
 loadedItem.time = dateFormatter.dateFromString(test)
 println("Time recorded as: \(loadedItem.time)")
 println("Time from server: " + test)

So, just edit date format hh to HH.

 dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

hope it helps

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136