Member-only story
Dealing With Date Serialization And Deserialization In JavaScript

There’s a little (intentional) hole in two of JavaScript’s widely used standard functions, namely in JSON.stringify
and JSON.parse
and it has to do with JavaScript's Date object. And this hole can sometimes lead so some headache.
We’ll take a look at what this hole actually is, and you’ll learn how you can effectively deal with it.
The Problem
Have you ever tried to JSON.stringify
an object which contains a Date? Works like a breeze, doesn't it?
const obj = {
date: new Date(),
id: "foo"
};const serialized = JSON.stringify(obj);
console.log(serialized);
// => prints {"date":"2020-12-03T09:19:29.408Z","id":"foo"}
But have you also tried to JSON.parse
the same object again, and then checked the type of the property that originally contained the date?
const deserialized = JSON.parse(serialized);
console.log(typeof deserialized.date);
// => prints string
Yes, it’s a string now.
The Reason For This Behavior
You might now ask something like “Why is JSON.parse not able to restore the date properly?” and it would be a very good question. Shouldn’t the function be able to determine…