Issue
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.
Solution
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.
Answered By - Firo Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.