JavaScript Date toJSON()
Syntax & Examples


Date.toJSON() method

The toJSON() method of the Date object in JavaScript returns a string representation of the Date object using the toISOString() method. This method is intended for use by JSON.stringify() to convert Date objects into JSON format.


Syntax of Date.toJSON()

The syntax of Date.toJSON() method is:

toJSON()

This toJSON() method of Date returns a string representing the Date using toISOString(). Intended for use by JSON.stringify().

Return Type

Date.toJSON() returns value of type String.



✐ Examples

1 Using toJSON() to get the JSON string of a Date object

In JavaScript, we can use the toJSON() method to get the JSON string representation of a Date object.

For example,

  1. We create a new Date object date representing January 1, 2000.
  2. We use the toJSON() method to get the JSON string of the date object.
  3. The JSON string is stored in the variable jsonString.
  4. We log jsonString to the console using console.log() method.

JavaScript Program

const date = new Date('2000-01-01T00:00:00Z');
const jsonString = date.toJSON();
console.log(jsonString);

Output

2000-01-01T00:00:00.000Z

2 Using toJSON() with the current date

We can use the toJSON() method to get the JSON string representation of the current date.

For example,

  1. We create a new Date object date representing the current date and time.
  2. We use the toJSON() method to get the JSON string of the date object.
  3. The JSON string is stored in the variable jsonString.
  4. We log jsonString to the console using console.log() method.

JavaScript Program

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

Output

Depends on the current date and time (e.g., '2024-05-27T12:34:56.789Z')

Summary

In this JavaScript tutorial, we learned about toJSON() method of Date: the syntax and few working examples with output and detailed explanation for each example.