Keep Fractional Seconds When Round-Tripping JSON Dates

The server sends 2026-11-18T12:34:56.123Z. Your app decodes it, edits an unrelated title, and sends the record back. The timestamp is now 2026-11-18T12:34:56Z.

Both sides used .iso8601. Apparently the encoder thought the milliseconds were optional, too.

For an API whose timestamps have millisecond resolution, configure decoding and encoding together. Test the outgoing JSON string and the instant it represents after decoding.

Download the complete example and checks.

The old fractional-seconds workaround changed

An answered Stack Overflow question about optional fractional seconds shows the longstanding workaround: try a fractional-seconds parser, then one without fractions. Keith Harrison’s custom Codable dates article explains why older .iso8601 decoding needed help.

That history matters when maintaining older deployment targets. Apple’s iOS 26 release notes explicitly say ISO8601FormatStyle now accepts fractional seconds regardless of includingFractionalSeconds. The property documentation describes the change in terms of Swift 6.2. The flag still controls formatting output.

On macOS 27.2.1 and the iOS 27.2 simulator, the same decoder accepted both "2026-11-18T12:34:56Z" and "2026-11-18T12:34:56.123Z" as the value of the timestamp field.

That matches the current Swift Foundation decoder implementation, which parses with Date.ISO8601FormatStyle().

The complete example targets iOS 26/macOS 26 or later. A newer compiler does not replace Foundation on an older iPhone. If you still support an earlier OS, retain your compatible parser and run the same fixtures there before removing its fallback. Compilation for an older target is not a runtime test of this behavior.

A successful decode is half the contract

Here’s the shortest way to watch the fraction disappear. A fresh JSONEncoder() uses .deferredToDate. This example explicitly selects .iso8601 on both sides, as a JSON API client might.

import Foundation

nonisolated struct Event: Codable, Equatable {
    var title: String
    let timestamp: Date
}

nonisolated func defaultDateRoundTrip() throws -> (Data, TimeInterval) {
    let incoming = Data(#"{"title":"Draft","timestamp":"2026-11-18T12:34:56.123Z"}"#.utf8)
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .iso8601
    let original = try decoder.decode(Event.self, from: incoming)

    let encoder = JSONEncoder()
    encoder.dateEncodingStrategy = .iso8601
    let outgoing = try encoder.encode(original)
    let restored = try decoder.decode(Event.self, from: outgoing)
    return (outgoing, restored.timestamp.timeIntervalSince(original.timestamp))
}

On both tested runtimes the outgoing timestamp omits .123. Decoding it again moves the event backward by approximately 0.123 seconds. The approximate wording accounts for Date’s floating-point representation. A printout that hides fractions can conceal the mistake, so compare values too.

This can matter even if the UI never displays milliseconds. Sorting, equality checks, deduplication, or a server’s change-detection logic may still use the value.

Make millisecond output explicit

This example handles ordinary event timestamps with millisecond-resolution values, a time zone, and seconds from 00 through 59. Leap-second and historical calendar conversions need a separate contract. Output uses UTC and exactly three fractional digits. The original offset spelling is not significant to this API.

A fractional Date.ISO8601FormatStyle looks like the obvious encoder. The macOS 27.2.1 research fixture caught another problem: it formatted 2026-11-18T12:34:56.002Z as .001Z. This off-by-one-millisecond issue is tracked in Swift Foundation. The issue links an upstream fix; that does not establish that the installed Foundation contains it.

For this tested codec, use a fixed-format DateFormatter with a POSIX locale, Gregorian calendar, and UTC. Apple’s fixed-format date guidance explains why the locale must be explicit. Before accepting output, parse it back and require the same Date. That turns unexpected precision loss into an encoding error.

nonisolated enum MillisecondJSON {
    private static let inputStyle = Date.ISO8601FormatStyle()

    static func makeDecoder() -> JSONDecoder {
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        return decoder
    }

    static func makeEncoder() -> JSONEncoder {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.calendar = Calendar(identifier: .gregorian)
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"

        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .custom { date, encoder in
            let wireValue = formatter.string(from: date)
            guard let restored = try? inputStyle.parse(wireValue),
                  restored == date else {
                throw EncodingError.invalidValue(
                    date,
                    .init(
                        codingPath: encoder.codingPath,
                        debugDescription: "Timestamp cannot be encoded at millisecond precision without changing its value."
                    )
                )
            }
            var container = encoder.singleValueContainer()
            try container.encode(wireValue)
        }
        return encoder
    }
}

The formatter stays private to this encoder and is configured before use. The check uses equality deliberately. It does not grant a small tolerance and quietly move the timestamp by that amount. The companion verifies all 1,000 millisecond positions across several representative dates, including dates before the Unix epoch and around Foundation’s reference date.

Even valid millisecond input can reach the error path. These two strings describe the same instant: 2000-12-31T12:00:00.001-12:00 and 2001-01-01T00:00:00.001Z. On the tested runtimes, Foundation decoded them to slightly different floating-point values. When asked to encode the first as UTC, the equality check rejected it. Adding a tolerance would let the save through, but would also change the value we promised to preserve.

If a server must accept every valid timestamp back exactly as issued, keep its original wire string and parse a separate value for display. If the API requires a UTC string on every write, parse the wire components directly into an integer count of milliseconds since a known epoch and format that value as UTC. The integer can stay inside your app. Converting an already-rounded Date to milliseconds cannot restore precision lost on input.

The checked Date encoder is useful for reading a record, editing another field, and returning its timestamp unchanged. An arbitrary Date.now, a calculated date, or an incoming microsecond value may fail it. If your product creates timestamps, choose and document a rounding policy at that creation boundary, or use the finer-precision representation your API requires. Do not silently introduce rounding while saving an otherwise unrelated edit.

Use the same pair for the actual payload

Add this function after the preceding declarations. The three Swift blocks in this article make one source file.

nonisolated func renameEvent(_ incoming: Data, to title: String) throws -> Data {
    let decoder = MillisecondJSON.makeDecoder()
    var event = try decoder.decode(Event.self, from: incoming)
    event.title = title
    return try MillisecondJSON.makeEncoder().encode(event)
}

Here Event models the entire two-field request body. A full replacement must carry every field the endpoint requires. Synthesized Codable drops keys your model never decoded. If the endpoint accepts a title-only update, send just the title and leave its timestamp alone.

If decoding or encoding throws, keep the user’s draft. Send the returned Data only after the whole encoding succeeds.

For 2026-11-18T12:34:56.123Z, the resulting timestamp remains 2026-11-18T12:34:56.123Z. For the equivalent input 2026-11-18T05:34:56.123-07:00, it also becomes that UTC spelling. A whole-second input becomes .000Z. Those are equivalent instants under this endpoint’s contract; they are not identical strings.

Do not use this codec to rewrite a server’s opaque cursor, signature input, or revision token merely because it looks like a date. Preserve those original values. The identifier article covers why interpretation and identity need different rules.

Keep precision and validation separate

Date is an instant represented with floating-point seconds. It is not a lossless container for an arbitrary timestamp string. Michael Tsai’s fractional-seconds discussion, including Ole Begemann’s experiments, prompted the precision checks here: successfully parsing nine digits does not mean a Date preserved all nine exactly.

The encoder’s equality check prevents additional loss when producing millisecond output. It cannot recover digits already lost while converting a finer timestamp to Date. Keep the original string or another suitable exact representation when those digits matter.

Also avoid treating Foundation’s acceptance as strict validation of your entire wire format. In the research probe, it accepted a timestamp followed by trailing text and normalized a February 30 date. This example assumes the endpoint supplies valid timestamps; it rejects strings Foundation cannot parse, but it is not an RFC 3339 validator. A strict boundary needs its own defined syntax and calendar validation.

Check the value that leaves the app

Unzip the sample, enter MillisecondJSON, and run python3 verify.py on an Apple silicon Mac with Xcode selected. The first check reproduces the 123-millisecond loss. The next edits the title and inspects both the outgoing string and the decoded instant. The rest cover offsets, epoch boundaries, invalid input and values the encoder must refuse.

The three Swift blocks compiled for iOS and macOS 26 targets with Xcode 27.2 and Swift 6.4.2. The complete checks pass on macOS 27.2.1 and iOS 27.2 Simulator in both ordinary and MainActor default-isolation modes. The sample uses established Foundation APIs; the relevant newer behavior is parsing optional fractions. Earlier runtimes and physical devices were not executed, and these tests do not establish exact nanosecond preservation.