views:

237

answers:

4

What's the date literal for JSON/JavaScript ( if such thing does exists? )

A: 

For string representation of date JSON uses string notation e.g. "2010-03-24 ...", and for object representation it uses object notation "{...}"

Mikhail
About the date, how does it knows that a string is a date and not a string if they use the same notation?
OscarRyz
+1  A: 

There is no special format for date literals.

In Javascript, you can write new Date(2010, 2, 23) (Months are zero-based, unfortunately).

SLaks
year - month - day right? What about JSON? What would be an accepted value for a date?
OscarRyz
Yes. For JSON, there is no standard; you'll need to use an ordinary string.
SLaks
And later, how to you use it in javascript? Should I do something like: `var myDate = new Date(jsonObj.date);` ???
OscarRyz
A: 

depends on the serializer.

it might be one of:

/Date(1224043200000)/

\/Date(1198908717056)\/ (MS JSON Date)

\/Date(1198908717056-1000)\/ (+/- timezone)

new Date("2010-03-24") (this is the generally accepted 'javascript json' from what I understand)

"2010-03-24"

etc

Luke Schafer
-1 That is not JSON.
Tomas
it's not _my_ fault there's no actual literal, and that each serializer is different, but this is a place for practical answers, not pedantic nitpicking.
Luke Schafer
+3  A: 

Date literals were proposed and then retracted, maybe we'll see them in a future edition of the ECMA-262 specification.

Since there is no Date literal in JavaScript, there is no literal for JSON either (JavaScript Object Notation wouldn't be too good a name if it couldn't be parsed by a JavaScript engine ;-)). Admittedly, this is unfortunate. Many web services will output an ISO 8601 string, e.g. 2010-03-23T23:57Z, but in order to parse it in JavaScript you would need to use a custom library, create a custom function or rely on ECMAScript 5th's Date parsing specification, which states that implementations should parse ISO 8601 strings natively.

If it's your own JSON that's going to be parsed in JavaScript, you could use something simple like milliseconds since January 1st 1970 00:00 with an identifier and then pass a reviver function to JSON.parse:

var myJSON = '{"MyDate":"@1269388885866@"}'
var myObj  = JSON.parse(myJSON, function (key, value)
{
   // Edit: don't forget to check the type == string!
   if (typeof value == "string" && value.slice(0, 1) == "@" && value.slice(-1) == "@")
       return new Date(+value.substring(1, -1));
   else
       return value;
}

Obviously, you'd need to use the native JSON object found in modern browsers or json2.js to use the reviver when parsing.

Andy E