6
struct TestEnc: Codable {
    var date = Date()
}
let encoder = JSONEncoder()
let tenc = TestEnc()
let jsonData = try encoder.encode(tenc)
let json = String(data: jsonData, encoding: String.Encoding.utf8)
print("json:\(json)")

This prints:

json:Optional("{\"date\":589331953.61679399}")

I can't find what this is supposed to represent in the documentation.

GoldenJoe
  • 7,874
  • 7
  • 53
  • 92
  • 1
    Please read [The Codable Cheat Sheet](https://www.hackingwithswift.com/articles/119/codable-cheat-sheet) – vadian Sep 05 '19 at 22:41
  • @vadian The cheat sheet does not mention Date encoding at all. Only decoding. – Darko Oct 03 '22 at 15:51

1 Answers1

8

iOS date are often encoded or processed as seconds from ReferenceDate

e.g. Date(timeIntervalSinceReferenceDate:)

Documentation for this is:

Summary

Creates a date value initialized relative to 00:00:00 UTC on 1 January 2001 by a given number of seconds.

Can run your number through this, and you will get your date back:

Date(timeIntervalSinceReferenceDate: 589331953.61679399)

output: "2019-09-04 23:19:13 +0000\n"


As far as the explicit encoding documentation goes. This is pretty terse.

There is a reference to the default encoding strategy in the documentation saying:

The default strategy is the JSONEncoder.DateEncodingStrategy.deferredToDate strategy.

However, there doesn't seem to be any clarity on what this actually means (beyond manual testing), reference is currently here. Even digging into the interface files, there doesn't seem to be any more light.

Firo
  • 15,448
  • 3
  • 54
  • 74