JSONDecoder.DateDecodingStrategy.iso8601 reject timestamps that include milliseconds like 2026-11-19T14:30:00.123Z. To parse and generate them, use Date.ISO8601FormatStyle(includingFractionalSeconds: true) or configure ISO8601DateFormatter with [.withInternetDateTime, .withFractionalSeconds].Why this happens
Most web APIs return UTC timestamps formatted according to ISO 8601 and RFC 3339 with millisecond or microsecond precision, such as 2026-11-19T02:29:40.920Z. However, Foundation’s default ISO 8601 utilities expect whole seconds only (2026-11-19T02:29:40Z).
When you pass a string containing .920Z to a default ISO8601DateFormatter, it returns nil. When you decode JSON using decoder.dateDecodingStrategy = .iso8601, JSONDecoder throws DecodingError.dataCorrupted with the message Expected date string to be ISO8601-formatted.
Developers often work around this by creating a custom DateFormatter with yyyy-MM-dd'T'HH:mm:ss.SSS'Z', which introduces two subtle bugs. First, omitting the en_US_POSIX locale causes formatting and parsing to break on devices set to non-Gregorian calendars (such as the Buddhist or Japanese calendars) or 12-hour clock overrides. Second, wrapping 'Z' in single quotes treats it as a literal character instead of a UTC timezone indicator, causing the formatter to misinterpret offsets or default to the user’s local timezone.
How to fix it
1. Use Date.ISO8601FormatStyle (iOS 15+ / macOS 12+)
In modern Swift, Date.ISO8601FormatStyle is the cleanest way to format and parse ISO 8601 timestamps. Unlike older formatter classes, it is a lightweight Sendable struct that automatically uses UTC (Z) and POSIX-safe calendar rules without manual setup.
Pass includingFractionalSeconds: true to its initializer to support milliseconds:
import Foundation
let style = Date.ISO8601FormatStyle(includingFractionalSeconds: true)
// Create an ISO 8601 UTC string with milliseconds
let nowString = Date.now.formatted(style)
// Example output: "2026-11-19T14:22:10.458Z"
// Parse an ISO 8601 string back into a Date
let rawTimestamp = "2026-11-19T14:22:10.458Z"
let parsedDate = try Date(rawTimestamp, strategy: style)
If you use this format across your project, extend FormatStyle and ParseStrategy so you can use dot-syntax anywhere Foundation expects a style or strategy:
import Foundation
extension Date.ISO8601FormatStyle {
static let iso8601WithFractionalSeconds = Self(includingFractionalSeconds: true)
}
extension FormatStyle where Self == Date.ISO8601FormatStyle {
static var iso8601WithFractionalSeconds: Date.ISO8601FormatStyle {
.iso8601WithFractionalSeconds
}
}
extension ParseStrategy where Self == Date.ISO8601FormatStyle {
static var iso8601WithFractionalSeconds: Date.ISO8601FormatStyle {
.iso8601WithFractionalSeconds
}
}
With those extensions in place, converting between Date and String takes one line:
let timestamp = Date.now.formatted(.iso8601WithFractionalSeconds)
let date = try Date(timestamp, strategy: .iso8601WithFractionalSeconds)
2. Decode and encode fractional seconds with Codable
Built-in JSONDecoder.DateDecodingStrategy.iso8601 cannot be configured to accept fractional seconds. Instead, define custom DateDecodingStrategy and DateEncodingStrategy extensions backed by Date.ISO8601FormatStyle.
In real-world backends, endpoints frequently omit .000 when a timestamp lands on an exact second (sending 2026-11-19T14:22:10Z alongside 2026-11-19T14:22:10.458Z). A strict fractional-seconds parser throws an error if the decimal part is missing. To make your Codable models resilient, try fractional seconds first and fall back to standard ISO 8601:
import Foundation
extension JSONDecoder.DateDecodingStrategy {
static let iso8601WithFractionalSeconds = custom { decoder in
let container = try decoder.singleValueContainer()
let dateString = try container.decode(String.self)
if let date = try? Date(
dateString,
strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)
) {
return date
}
if let date = try? Date(
dateString,
strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: false)
) {
return date
}
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Invalid ISO 8601 date string: \(dateString)"
)
}
}
extension JSONEncoder.DateEncodingStrategy {
static let iso8601WithFractionalSeconds = custom { date, encoder in
var container = encoder.singleValueContainer()
let formatted = date.formatted(
Date.ISO8601FormatStyle(includingFractionalSeconds: true)
)
try container.encode(formatted)
}
}
Apply these strategies directly to your JSONDecoder and JSONEncoder instances:
struct Event: Codable {
let id: Int
let createdAt: Date
}
let json = Data(#"{"id": 1, "createdAt": "2026-11-19T02:11:29.158Z"}"#.utf8)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601WithFractionalSeconds
let event = try decoder.decode(Event.self, from: json)
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601WithFractionalSeconds
let encodedData = try encoder.encode(event)
3. Use ISO8601DateFormatter with formatOptions
If you prefer returning an optional Date? instead of catching thrown errors—or if you are working in an older Objective-C/Foundation codebase—use ISO8601DateFormatter and include .withFractionalSeconds alongside .withInternetDateTime.
import Foundation
enum ISO8601Parser {
private static let fractionalFormatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return formatter
}()
static func string(from date: Date) -> String {
fractionalFormatter.string(from: date)
}
static func date(from string: String) -> Date? {
fractionalFormatter.date(from: string)
}
}
Avoid instantiating ISO8601DateFormatter inside loops or SwiftUI view bodies. Allocating Foundation formatter classes repeatedly adds noticeable CPU overhead when parsing large arrays. Note also that under strict Swift concurrency checking, ISO8601DateFormatter is a mutable reference type and is not Sendable, making Date.ISO8601FormatStyle from Fix 1 the safer choice in async functions and actors.
4. Configure DateFormatter safely with en_US_POSIX (RFC 3339 fallback)
If you must use DateFormatter to handle a non-standard variation of RFC 3339, follow Apple’s Technical Q&A QA1480 guidelines for fixed-format dates:
- Set
localetoLocale(identifier: "en_US_POSIX"). - Set
calendartoCalendar(identifier: .iso8601). - Set
timeZonetoTimeZone(secondsFromGMT: 0). - Use
XXXXX(orZZZZZ) instead of'Z'indateFormat.
import Foundation
extension DateFormatter {
static let rfc3339Fractional: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
}
Using XXXXX outputs Z when the formatter’s timezone is UTC, while properly parsing both Z and explicit numeric offsets like -03:00 or +02:00 in incoming strings.
How to prevent it
- Default to
Date.ISO8601FormatStylein new Swift code: It eliminates locale bugs, calendar mismatches, and Swift concurrency warnings because it is an immutable value type. - Never quote
'Z'indateFormatstrings: Writing'Z'strips timezone awareness and parses incoming UTC dates as local time unless you manually lock the timezone. - Support both fractional and whole seconds when decoding JSON: Many server frameworks strip
.000automatically when milliseconds equal zero, which breaks strict fractional-only decoders in production. - Cache class-based formatters: If you use
ISO8601DateFormatterorDateFormatter, store them once asstatic letproperties rather than recreating them per request.
FAQ
Why does JSONDecoder.DateDecodingStrategy.iso8601 fail on milliseconds?
Under the hood, .iso8601 uses a default ISO8601DateFormatter configured only with .withInternetDateTime. Because .withFractionalSeconds is not enabled on that default strategy, any decimal point after the seconds field triggers a DecodingError.dataCorrupted failure.
What happens if an API mixes dates with and without fractional seconds?
Both Date.ISO8601FormatStyle(includingFractionalSeconds: true) and ISO8601DateFormatter with .withFractionalSeconds require fractional digits to be present when enabled. To handle mixed payloads safely, try parsing with fractional seconds enabled first, then fall back to includingFractionalSeconds: false if the first attempt fails.
Why is en_US_POSIX required on DateFormatter?
By default, DateFormatter respects the user’s region and calendar settings in iOS and macOS Settings. Without en_US_POSIX, a user with a Buddhist calendar will generate years offset by 543 years (for example, 2569 instead of 2026), and 12-hour time settings can corrupt HH hour formatting.
Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.