Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript/json date literal

Tags:

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

like image 762
OscarRyz Avatar asked Mar 23 '10 22:03

OscarRyz


People also ask

How do you format a date in JSON?

There is no date format in JSON, there's only strings a de-/serializer decides to map to date values. However, JavaScript built-in JSON object and ISO8601 contains all the information to be understand by human and computer and does not relies on the beginning of the computer era (1970-1-1).

Does JSON have date type?

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 new date () in JavaScript?

The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.

What does new date () return?

"The expression new Date() returns the current time in internal format, as an object containing the number of milliseconds elapsed since the start of 1970 in UTC.


2 Answers

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.

like image 81
Andy E Avatar answered Sep 20 '22 19:09

Andy E


There is no special format for date literals.

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

like image 36
SLaks Avatar answered Sep 18 '22 19:09

SLaks