Issues with Date() when using JSON.stringify() and JSON.parse()

If you look at the output of JSON.stringify for a Date, you’ll see that:

JSON.stringify(new Date())

Results in a string. JSON does not have a primitive representation of Date objects that JSON.parse will turn back into a Date object automatically.

The Date object’s constructor can take a date string, so you can turn those string values back into dates by doing:

var x = new Date(JSON.parse(JSON.stringify(new Date())));

Then the arithmetic will work.

x = new Date(JSON.parse(JSON.stringify(new Date())))
y = new Date(JSON.parse(JSON.stringify(new Date())))
y - x
=> 982

Leave a Comment