Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Unfortunately, there is no "date literal" in JavaScript (arrays can be expressed with <code>[]</code> and objects with <code>{}</code>, but no such love for Date objects). As well, actual, valid JSON only accepts primitive values (like strings, numbers, arrays, booleans, objects and not much else). You may also be surprised to learn that the <code>Date()</code> in JSON is not valid (though that's not a problem if you don't care about portability). </p> <p>If you have control over the code that produces the feed and consumes it, though, you may want to do one of a couple things. First, pass the date as a timestamp. This is easy enough:</p> <pre><code>var dtDateTime = new Date('Jan 27 2011 00:00:00 GMT+0000'); var intDateTime = dtDateTime.getTime(); var objJSON = { "datetime":intDateTime }; </code></pre> <p>After loading the JSON, your code would then parse the <code>datetime</code> with:</p> <pre><code>var dtDateTime = new Date(); dtDateTime.setTime(objJson.datetime); </code></pre> <p>Here, your code would have to expect the <code>datetime</code> property and know to decode it. So it's not a great generalized solution.</p> <p>Another way I've seen this nut cracked is with a special string literal, that signifies to your script that it is a datetime. It could be in the value:</p> <pre><code>var objJSON = { "datetime":"@Jan 27 2011 00:00:00GMT+0000@" }; </code></pre> <p>Or it could be name:</p> <pre><code>var objJSON = { "@datetime":1296086400000 }; </code></pre> <p>The <code>@</code> simply acts as a flag to your code that the value needs some sort of post-processing. Both will pass validation.</p> <p>JSON is meant to be simple and cross-platform, so anything that is specific to JS is inherently bad. If you tried to load JSON into, say Java or C#, you'd have a problem.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload