Date.prototype.toJSON()

The toJSON() method returns a string representation of the Date object.

Try it

Syntax

toJSON()

Return value

A string representation of the given date.

Description

Date instances refer to a specific point in time. toJSON() calls the object's toISOString() method, which returns a string representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization, which can then be deserialized using the Date() constructor or Date.parse() as the reviver of JSON.parse().

Examples

Using toJSON()

const jsonDate = new Date().toJSON();
const backToDate = new Date(jsonDate);

console.log(jsonDate); // 2015-10-26T07:46:36.611Z

Serialization round-tripping

When parsing JSON containing date strings, you can use Date.parse() to revive them into the original date objects.

const fileData = {
  author: "John",
  title: "Date.prototype.toJSON()",
  createdAt: new Date(2019, 3, 15),
  updatedAt: new Date(2020, 6, 26),
};
const response = JSON.stringify(fileData);

// Imagine transmission through network

const data = JSON.parse(response, (key, value) => {
  if (key === "createdAt" || key === "updatedAt") {
    return Date.parse(value);
  }
  return value;
});

console.log(data);

Specifications

Specification
ECMAScript Language Specification
# sec-date.prototype.tojson

Browser compatibility

BCD tables only load in the browser

See also