2

I get the following date back from an API.

{
  "createdDate": "2019-03-22T15:53:06.663Z"
}

I'd like to decode this and store it as a Date type.

My JSONDecoder is not able to decode this however.

I have tried to extend it with

extension DateFormatter {
    static let iso8601Full: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.locale = Locale(identifier: "en_US_POSIX")
        return formatter
    }()
}

and then using decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601Full) but this does not work

Tim J
  • 1,211
  • 1
  • 14
  • 31

1 Answers1

2

Use ISO8601DateFormatter with formatting options

let str = "2019-03-22T15:53:06.663Z"
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withFullDate, .withFullTime, .withTimeZone, .withFractionalSeconds]
let date = formatter.date(from: str)
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • 1
    or simply `[.withInternetDateTime, .withFractionalSeconds]`. Btw you can't use ISO8601DateFormatter with `dateDecodingStrategy`. You would need to create a custom Date decoding strategy. https://stackoverflow.com/questions/28016578/how-to-create-a-date-time-stamp-and-format-as-iso-8601-rfc-3339-utc-time-zone/28016692#28016692 – Leo Dabus Mar 23 '19 at 21:57