4

What is the best way to deserialize a JSON date into an NSDate instance using SwiftyJSON?

Is it to just use stringValue with NSDateFormatter or is there a built in date API method with SwiftyJSON?

Community
  • 1
  • 1
Marcus Leon
  • 55,199
  • 118
  • 297
  • 429

2 Answers2

13

It sounds like NSDate support isn't built in to SwiftyJSON, but you can extend the JSON class with your own convenience accessors.

The following code is adapted from this GitHub issue.

extension JSON {
    public var date: NSDate? {
        get {
            if let str = self.string {
                return JSON.jsonDateFormatter.dateFromString(str)
            }
            return nil
        }
    }

    private static let jsonDateFormatter: NSDateFormatter = {
        let fmt = NSDateFormatter()
        fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
        fmt.timeZone = NSTimeZone(forSecondsFromGMT: 0)
        return fmt
    }()
}

Example:

let j = JSON(data: "{\"abc\":\"2016-04-23T02:02:16.797Z\"}".dataUsingEncoding(NSUTF8StringEncoding)!)

print(j["abc"].date)  // prints Optional(2016-04-23 02:02:16 +0000)

You might need to tweak the date formatter for your own data; see this question for more examples. Also see this question about date formatting in JSON.

Community
  • 1
  • 1
jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • Thanks, this looks great. Yes I have to tweak my date formatting. It's not working now with an example date of `2016-04-24T16:47:58.319+0000`. Not sure why this doesn't jive with the `NSDateFormatter` format that you mention in the answer. – Marcus Leon Apr 24 '16 at 16:55
  • Because the dateFormat I used doesn't accept time zone information. Look at the other questions I linked; I think the answers include an example that does. – jtbandes Apr 24 '16 at 17:52
3

Swift 3 Version

extension JSON {
    public var date: Date? {
        get {
            if let str = self.string {
                return JSON.jsonDateFormatter.date(from: str)
            }
            return nil
        }
    }

    private static let jsonDateFormatter: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
        dateFormatter.timeZone = TimeZone.autoupdatingCurrent
        return dateFormatter
    }()
}
dbergman
  • 98
  • 9