How do I format JSON Date String with Swift?

Nearpoint picture Nearpoint · Feb 26, 2015 · Viewed 26.7k times · Source

I make an http get request to a server and get back a json object with a date string like this:

{
    name = "Place1";
    temperature = 79;
    humidity = 68;
    reported_at = "2013-07-21T19:32:00Z";
}

I want to format the reported_at key so I can display a readable date and time to the user.

This is the swift code I am trying which keeps returning nil, as it cannot format the date.

    var str = "2013-07-21T19:32:00Z"

    var dateFor: NSDateFormatter = NSDateFormatter()
    dateFor.dateFormat = "yyyy-MM-dd'T'HH:mm:ss:SSS"

    var yourDate: NSDate? = dateFor.dateFromString(str)

    println(yourDate)

How can I format this date and time with Swift correctly? I want to display the date and time to the user so they can know when the reading was taken.

Answer

Zell B. picture Zell B. · Feb 26, 2015

Use the following string format to convert a server string into a Date

dateFor.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"