API · JavaScript

JavaScript Date.toJSON() Method

In JavaScript, the date.toJSON() method changes the date mentioned in a date object into a date and time of the ISO standard.

The date.toJSON() method uses the ISO standard to convert the date object into a string without any parameter. This method uses the YYYY-MM-DDTHH:mm:ss.sssZ format to change the date and time.

Syntax of JavaScript date.toJSON() Method

date.toJSON();

Return

Using ISO standards, this method takes a date object to return a string.

Example Codes: Use of date.toJSON() Method to Convert a Date Object Into a String

const date = new Date('2022, 8, 17, 14:13:05');
let json = date.toJSON();
console.log(json);

Output:

2022-08-17T21:13:05.000Z

We created a date object and used the date.toJSON() method to convert a date object into a string that follows the ISO format.

Example Codes: Use of date.toJSON() to Check the Difference in the Time Format of ISO Standard

const date = new Date('2022, 4, 17');
let json = date.toJSON();
const d = new Date('2022, 4, 17, 1:20:05');
let jso = d.toJSON();
console.log(json);
console.log(jso);

Output:

2022-04-17T00:00:00.000Z
2022-04-17T01:20:05.000Z

When we don’t pass the time to the Date object, it considers the time as 00:00:000 and converts the date string to ISO format.

The Date.toJSON() method works on most browsers of the current version. This method returns the same output as the .toISOString() method.