JavaScript date.toJSON() method


The date.toJSON() method in JavaScript is used to convert a Date object into a JSON-compatible string format. It internally uses the toISOString() method, returning the date and time in ISO 8601 format.

Syntax:

date.toJSON();

Returns:

  • A string representing the date in ISO 8601 format, similar to the output of toISOString(), in the format: YYYY-MM-DDTHH:mm:ss.sssZ.

Key Features:

  • The toJSON() method is typically used when serializing Date objects to JSON (e.g., when using JSON.stringify()).
  • It ensures that dates are stored in a consistent, universally accepted format.

Example 1: Converting the Current Date to JSON

const date = new Date(); console.log(date.toJSON());

Output:

2024-10-22T10:45:30.456Z

Explanation:

  • The toJSON() method converts the current date to a string in the ISO 8601 format.
  • The time is expressed in UTC (indicated by Z), and milliseconds are included.

Example 2: Serializing a Date Object with JSON.stringify()

const obj = { event: "Conference", date: new Date() }; console.log(JSON.stringify(obj));

Output:

{ "event": "Conference", "date": "2024-10-22T10:45:30.456Z" }

Explanation:

  • When using JSON.stringify() to convert an object containing a Date, the Date object is automatically serialized to a JSON-compatible string using the toJSON() method.
  • The date is represented in ISO format inside the JSON structure.

Example 3: Using toJSON() with a Specific Date

const specificDate = new Date('July 20, 1969 20:18:00'); console.log(specificDate.toJSON());

Output:

1969-07-20T20:18:00.000Z

Explanation:

  • The toJSON() method converts the specific date (July 20, 1969 20:18:00) into ISO 8601 format.
  • The time zone is adjusted to UTC, and milliseconds are included as .000.

Example 4: toJSON() on Invalid Date

const invalidDate = new Date("invalid"); console.log(invalidDate.toJSON());

Output:

null

Explanation:

  • If the Date object is invalid, toJSON() returns null instead of a string.

Summary:

  • date.toJSON() is used to convert a Date object into a JSON-compatible ISO 8601 string format.
  • It is often invoked automatically during JSON.stringify() and is especially useful when serializing objects containing Date values.
  • The result is always in UTC, and it returns null for invalid Date objects.