Categories
JavaScript Answers

How to JSON stringify a JavaScript Date and preserve time zone?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *