Converting a date from JSON to NSDate using Swift

I had a lot of difficulty getting a date from a REST service and then using within my Swift code. Actually the only difficulty was converting the REST data into something that Swift was happy with.

Let’s assume that you have made your rest call and retrieved your data. In my case, dates could be null so I’m performing an ‘if let’ statement to make sure I get a valid value before trying to convert it. Then I call a function I named ‘getDate(…)’ to turn the string into a NSDate.

Here are the important bits of this process:




...
 if let dueDate = elem["DueDate"] as? NSString
 {
                t.DueDate = getDate(dueDate)
 }
...

And here is the getDate function:

    func getDate(dateString:NSString) -> NSDate{
       
       
        var dateFormatter = NSDateFormatter()

        if(dateString.length == 19)
        {
            dateFormatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss" //This is the format returned by .Net website
        }
        else if(dateString.length == 21)
        {
            dateFormatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.S" //This is the format returned by .Net website
        }
        else if(dateString.length == 22)
        {
            dateFormatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.SS" //This is the format returned by .Net website
        }
        else if(dateString.length == 23)
        {
             dateFormatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.SSS"
        }

        var date = dateFormatter.dateFromString(dateString)
        
        
        return date!;
        
    }

2 thoughts on “Converting a date from JSON to NSDate using Swift

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s