Sometimes, we want to JSON stringify a JavaScript Date and preserve time zone.
In this article, we’ll look at how to JSON stringify a JavaScript Date and preserve time zone.
How to JSON stringify a JavaScript Date and preserve time zone?
To JSON stringify a JavaScript Date and preserve time zone, we can create our own replacer function.
For instance, we write
const replacer = function (key, value) {
if (this[key] instanceof Date) {
return this[key].toUTCString();
}
return value;
};
console.log(JSON.stringify(new Date(), replacer));
console.log(JSON.stringify({ myProperty: new Date() }, replacer));
to define the replacer
function.
In it, we check if the this[key]
property is a Date
.
this
is the object being stringified.
If it is, then we stringify it as a UTC string with toUTCString
.
Otherwise, we return value
as is.
Then we call JSON.stringify
with values we want to convert to JSON strings and use replacer
to do stringify the properties or values.
Conclusion
To JSON stringify a JavaScript Date and preserve time zone, we can create our own replacer function.