PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, December 4, 2022

[FIXED] What is the default date format Swift uses for JSONEncoder?

 December 04, 2022     codable, ios, json, jsonencoder, swift     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing