skip to content

Why does Swift's JSONDecoder at default settings throw typeMismatch on an ISO 8601 date string, and which dateDecodingStrategy fixes it?

level: middleimportance: should knowfreq 55%

answer

  1. default defers to Date itself
  2. a number, not a string
  3. the 2001 reference date
  4. one strategy per decoder

basics

~20 s

The default .deferredToDate lets Date decode itself, which expects a number of seconds since 1 January 2001, so a string throws typeMismatch. Set dateDecodingStrategy to .iso8601, or to .custom when one payload mixes date formats.

solid answer

~40 s

`JSONDecoder.dateDecodingStrategy` defaults to `.deferredToDate`, which hands the value to `Date`'s own `init(from:)`. That reads a `Double`: seconds since the reference date, 1 January 2001 UTC. An ISO 8601 string therefore fails with `DecodingError.typeMismatch` and the description "Expected to decode Double but found a string instead." Set `.iso8601` for RFC 3339 strings, `.secondsSince1970` or `.millisecondsSince1970` for Unix timestamps, `.formatted(_:)` for a fixed `DateFormatter` pattern, or `.custom` with a closure that reads a `singleValueContainer()` when formats vary. The strategy applies to every `Date` the decoder reads, at any depth. `JSONEncoder` has the same default, so the encoder needs a matching `dateEncodingStrategy` or the server receives reference-date seconds.

code

swift · 20 lines
swift
import Foundation

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom { decoder in
    let container = try decoder.singleValueContainer()
    if let seconds = try? container.decode(Double.self) {
        return Date(timeIntervalSince1970: seconds)
    }
    let text = try container.decode(String.self)
    if let date = try? Date.ISO8601FormatStyle().parse(text) {
        return date
    }
    throw DecodingError.dataCorruptedError(
        in: container, debugDescription: "Unrecognized date: \(text)")
}

struct Reading: Decodable { let observedAt: Date }
let json = #"[{"observedAt": 1791619200}, {"observedAt": "2026-10-10T08:00:00Z"}]"#
let readings = try decoder.decode([Reading].self, from: Data(json.utf8))
print(readings.map(\.observedAt))

go deeper

for a junior

Recall that JSONDecoder needs dateDecodingStrategy set to .iso8601 before it reads date strings.

for a middle

Explain that the default defers to Date, which reads seconds since 2001, and list the other built-in strategies with what each expects.

for a senior

Decide what to do with mixed or ambiguous formats: a custom strategy that throws dataCorrupted, or a String-typed field for calendar days.

for a principal

Make the wire date format an explicit, tested contract on both encoder and decoder, owned in one shared configuration rather than per call site.

## The default is not a string format `JSONDecoder.dateDecodingStrategy` decides how every `Date` in a payload is read. Its default is **`.deferredToDate`**, documented as "Defer to `Date` for decoding". `Date`'s own `Decodable` conformance reads a single **number**: the seconds since the **reference date**, 1 January 2001 at 00:00 UTC. That is Foundation's internal representation, not a format any server is likely to send. So when a weather API sends `"observedAt": "2026-10-10T08:00:00Z"`, decoding stops at that key with: - **`DecodingError.typeMismatch`**, expected type `Double`; - a coding path ending in `observedAt`; - the debug description "Expected to decode Double but found a string instead." The error names `Double`, not `Date`, which is the clue that the default strategy is still in place. ## The built-in strategies | Strategy | Expects in JSON | Notes | |---|---|---| | `.deferredToDate` | number, seconds since 2001-01-01 UTC | the default | | `.secondsSince1970` | number, Unix seconds | fractional values allowed | | `.millisecondsSince1970` | number, Unix milliseconds | common in JavaScript-backed APIs | | `.iso8601` | string, ISO 8601 in RFC 3339 form | time-zone offsets such as `+02:00` are honoured | | `.formatted(DateFormatter)` | string in the formatter's format | Apple platforms' Foundation; set `locale` to `en_US_POSIX` | | `.custom(_:)` | anything your closure reads | the closure gets the `Decoder` and returns a `Date` | A string that `.iso8601` cannot parse throws `DecodingError.dataCorrupted` with the description "Expected date string to be ISO8601-formatted.", and its coding path stops at the enclosing object instead of naming the date key; a number under `.iso8601` throws `typeMismatch` for `String`. ## One strategy per decoder The strategy is a property of the decoder, so it applies to **every** `Date` decoded through it, at any depth, including dates your own `init(from:)` reads with `container.decode(Date.self, forKey:)`. Three consequences follow: 1. A payload that mixes formats, Unix seconds in one field and ISO strings in another, needs `.custom` or a dedicated decoder per endpoint. 2. Sharing one configured decoder across the app is a reasonable default, but a change to its strategy changes every model it decodes. 3. A date that should stay a string, for example a local calendar day such as `"2026-10-10"` without a time, is better modelled as a `String` or a small wrapper type than forced through a date strategy that will invent a time zone. ## Offsets, fractions and the OS `JSONDecoder` ships with the operating system, so its date parsing can differ between the OS releases an app supports. On the Swift 6.4 toolchain's Foundation, `.iso8601` accepted `2026-10-10T08:00:00Z`, `2026-10-10T08:00:00.250Z` and `2026-10-10T08:00:00+02:00`, converting the offset to the correct UTC instant. Rather than relying on a rule remembered from an older release, keep a recorded payload with the exact date strings your server sends and decode it in a unit test run on the oldest OS you support. When a date fails, the error itself tells you which situation you are in: - `typeMismatch` expecting `Double`: the default strategy is still set; - `typeMismatch` expecting `String`: `.iso8601` or `.formatted` met a number; - `dataCorrupted` mentioning ISO8601: the string is not in a form the parser accepts. ## Writing a `.custom` strategy The closure receives the `Decoder` positioned at the date value. Open a `singleValueContainer()`, try the shapes you accept, and throw with `DecodingError.dataCorruptedError(in:debugDescription:)` so the error still carries the coding path. The closure is `@Sendable`, so capture only immutable or sendable state; `Date.ISO8601FormatStyle` is a value type, which makes it a convenient parser inside the closure. ## The encoder has the same default `JSONEncoder.dateEncodingStrategy` also defaults to `.deferredToDate`, so encoding 10 October 2026 writes a number around `813312000`, the seconds since 2001. A server that reads it as Unix seconds sees a date about 31 years earlier, in 1995. When the app sends dates back, set the encoder's strategy to match the decoder's, for example `.iso8601` on both, and cover the pair with a round-trip test.

  • Why does the error name `Double` rather than `Date`?
    Under `.deferredToDate` the decoder delegates to `Date`'s own `init(from:)`, which asks a single-value container for a `Double`. The mismatch is detected at that inner request, so the error reports `Double` at the date's coding path.
  • How should a `.custom` date strategy report a value it cannot parse?
    Throw `DecodingError.dataCorruptedError(in:debugDescription:)` with the single-value container it opened. That builds a `dataCorrupted` error whose context carries the container's coding path, so the failure still points at the exact field, unlike a generic error thrown from the closure.

  • JSONDecoder parses ISO 8601 date strings by default.
  • The default date strategy reads Unix seconds since 1970.
  • dateDecodingStrategy can be set per property in the model.
  • JSONEncoder writes dates as ISO 8601 strings unless told otherwise.