Understanding date decoding strategies when working with JSON in Swift
Learn how to convert JSON dates to Swift's native Date type and vice versa.
14 Nov 2022 · 2 min read
When converting a JSON date into Swift's native Date type and vice versa, the JSON decoder and encoder provide different date coding strategies. We can choose between the following strategies:
- .deferredToDate
- .iso8601
- .millisecondsSince1970
- .secondsSince1970
- .formatted(DateFormatter)
- .custom((Decoder) -> Date)
In this article, we are going to look at each strategy in more detail. Let's get started.

Strategy .deferredToDate
The .deferredToDate strategy is the default strategy which uses Apple's own date format. It is a number of seconds relative to midnight UTC on 1. January 2001. When encoding the date as follows:
let jsonEncoder = JSONEncoder()jsonEncoder.dateEncodingStrategy = .deferredToDatelet article = Article(date: Date())let encodedArticle = try jsonEncoder.encode(article)print(String(data: encodedArticle, encoding: .utf8)!)
We get the following output:
{ "date" : 695980776.16554499 }
Strategy .iso8601
The .iso8601 strategy formats dates according to the ISO 8601 standard which is an international standard covering worldwide exchange of date and time-related data.
When changing our example above to this strategy, we get the following output:
{ "date" : "2023-01-21T07:59:36Z" }
The T character is a time identifier that precedes the time value.
The Z character is a time zone identifier indicating that the time zone is UTC. It only needs to be appended to the time value.
Strategy .millisecondsSince1970
This strategy decodes dates in milliseconds since midnight UTC on January 1st, 1970.
{ "date" : 1674287976165.5449 }
Strategy .secondsSince1970
This strategy decodes dates in seconds since midnight UTC on January 1st, 1970.
{ "date" : 1674287976.165545 }
Strategy .formatted(DateFormatter)
This strategy allows us to set any custom date formatter, for example:
let dateFormatter = DateFormatter()dateFormatter.dateFormat = "yyyy-MM-dd"jsonEncoder.dateEncodingStrategy = .formatted(dateFormatter)
Which provides the following output:
{ "date": "2023-01-21" }
Strategy .custom((Decoder) -> Date)
This strategy gives us the most flexibility, for example if we need to add some conditions to the date encoding.
jsonEncoder.dateEncodingStrategy = .custom({ date, encoder invar container = encoder.singleValueContainer()try container.encode("Some custom date encoding \(date.description)")})
Which provides the following output:
{ "date": "Some custom date encoding 2023-01-21 07:59:36 +0000" }

Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips