mankee mankee - 6 months ago 18
Swift Question

String into NSDate Swift2

I obtain the following string from my JSON response :

2016-05-24 17:13:08


I use the following code to parse it into an
NSDate
:

if let messagedate = onemessage["timestamp"] as? String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let date = dateFormatter.dateFromString(messagedate)
curr_message.date = date
}


where
curr_message
is of type
Message
initialised like this :

class Message : NSObject {
var id: String?
var text: String?
var date: NSDate?
var sender: Friend?
}


The problem is that the
curr_message.date
value is always
nil
after this
if
condition executes.

Answer

Use "HH" instead of "hh" for dateFormatter.dateFormat.

"hh" is for AM/PM format, "HH" is for 24 hours format, and you have the latter: 17:13:08.