NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

Time and Date Decoding

Forums > Swift

Can anyone suggest how to decode the following JSON elements

    "upload-time": "2008-10-13T10:40:02.000Z",
    "duration": "PT2H44M"

The first looks to me like RFC 3339 - RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" ???

The publisher of the second states - "The time interval as specified in ISO 8601"


For upload-time, which is not quite ISO 8601 format, you need to use a custom formatter, like so:

let formatter = DateFormatter()
formatter.dateFormat = "YYYY-MM-DD'T'HH:mm:ss.SSS'Z'"

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)

There is no built-in Swift way to decode the ISO 8601 duration format, which is what duration is in. For that you would need to work on converting from a string (to maybe a TimeInterval?) yourself, or use a third-party library, like this one: Swift-ISO8601-DurationParser.


use let formatter = ISO8601DateFormatter()


ISO8601DateFormatter doesn't handle fractional seconds (the .000 part of the given data) by default. You have to do:

let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]

But then you can't assign it as the custom date decoding strategy for JSONDecoder using .formatted(DateFormatter) because ISO8601DateFormatter is not a subclass of DateFormatter (they are both subclasses of Formatter).

And using decoder.dateDecodingFormat = .iso8601 also won't work because of the fractional seconds and there's no way to change the options this time.

You could use ISO8601DateFormatter if you handled the decoding manually, by pulling out upload-time as a string and then applying the formatter to it, but you would have to then handle all the other keys in the JSON too, and that may not be what the OP is looking for.


Hacking with Swift is sponsored by Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

Not logged in

Log in

Link copied to your pasteboard.