Logo for tanaschita.com

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:

In this article, we are going to look at each strategy in more detail. Let's get started.

Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

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 = .deferredToDate
let 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 in
var 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" }
Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

networking

swift

ios

Understanding different cache policies when working with URLRequest in Swift

Learn how to manage cache when sending HTTP requests in your iOS applications.

31 Oct 2022 · 4 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum