NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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 Fernando Olivares

SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.

Try the book!

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.