JSON - Storing date vs storing date.toString (v3)

Revision 3 of this benchmark created by Dan Manastireanu on


Description

JSON.parse(JSON.stringify(new Date())) isn't the same as new Date(JSON.parse(JSON.stringify(new Date()))).

The strange thing is that new Date(JSON.parse(JSON.stringify(d))) !== new Date(JSON.parse(JSON.stringify(d.toString()))) ... anyone know why that is?


The difference is in the milliseconds part.
The toString() function returns a pretty representation of the date, to be used as display to humans. This representation doesn't have any information about the milliseconds.

You can use getTime() to get the total number of milliseconds since 1970...

Or you can get a complete string representation by calling toJSON or toISOString

See updated examples, Dan M.

Preparation HTML

<script>
  var date = new Date();
  var s1 = JSON.stringify(date),
      s2 = JSON.stringify(date.toString());
  var d1 = new Date(JSON.parse(s1)),
      d2 = new Date(JSON.parse(s2));
  
  //output information to console (firebug etc.)
  console.log('Original Date.time = ' + date.getTime());
  console.log('Raw JSON Date[' + s1 + '].time = ' + d1.getTime());
  console.log('String JSON Date[' + s2 + '].time = ' + d2.getTime());
  console.log('Raw - String = ' + (d1 - d2) + ' ms');
  
  //alert(date.getTime() + '\n' + s1 + ' = ' + d1.getTime() + '\n' + s2 + ' = ' + d2.getTime());
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Raw date
new Date(JSON.parse(JSON.stringify(date)));
ready
String date
//looses the milliseconds
new Date(JSON.parse(JSON.stringify(date.toString())));
ready
As number
new Date(JSON.parse(JSON.stringify(date.getTime())));
ready
toJSON
//redundant call to toJSON, since stringify already does that
new Date(JSON.parse(JSON.stringify(date.toJSON())));
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published on
  • Revision 2: published by Sami Samhuri on
  • Revision 3: published by Dan Manastireanu on