Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "right" JSON date format?

I've seen so many different standards for the JSON date format:

"\"\\/Date(1335205592410)\\/\""         .NET JavaScriptSerializer "\"\\/Date(1335205592410-0500)\\/\""    .NET DataContractJsonSerializer "2012-04-23T18:25:43.511Z"              JavaScript built-in JSON object "2012-04-21T18:25:43-05:00"             ISO 8601 

Which one is the right one? Or best? Is there any sort of standard on this?

like image 588
Kamyar Nazeri Avatar asked Apr 23 '12 18:04

Kamyar Nazeri


People also ask

How should a date be stored in JSON?

JSON does not have a built-in type for date/time values. The general consensus is to store the date/time value as a string in ISO 8601 format.

What is standard JSON format?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

Is date valid type in JSON?

Format. The format keyword allows for basic semantic identification of certain kinds of string values that are commonly used. For example, because JSON doesn't have a “DateTime” type, dates need to be encoded as strings.

Which date format is best for?

The international standard recommends writing the date as year, then month, then the day: YYYY-MM-DD. So if both Australians and Americans used this, they would both write the date as 2019-02-03.


2 Answers

JSON does not know anything about dates. What .NET does is a non-standard hack/extension.

I would use a format that can be easily converted to a Date object in JavaScript, i.e. one that can be passed to new Date(...). The easiest and probably most portable format is the timestamp containing milliseconds since 1970.

like image 32
ThiefMaster Avatar answered Oct 19 '22 23:10

ThiefMaster


JSON itself does not specify how dates should be represented, but JavaScript does.

You should use the format emitted by Date's toJSON method:

2012-04-23T18:25:43.511Z

Here's why:

  1. It's human readable but also succinct

  2. It sorts correctly

  3. It includes fractional seconds, which can help re-establish chronology

  4. It conforms to ISO 8601

  5. ISO 8601 has been well-established internationally for more than a decade

  6. ISO 8601 is endorsed by W3C, RFC3339, and XKCD

That being said, every date library ever written can understand "milliseconds since 1970". So for easy portability, ThiefMaster is right.

like image 135
funroll Avatar answered Oct 19 '22 22:10

funroll