UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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"

2      

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.

2      

use let formatter = ISO8601DateFormatter()

2      

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.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.