JavaScript Date.toJSON() Method

Shubham Vora Jan 30, 2023
  1. Syntax of JavaScript date.toJSON() Method
  2. Example Codes: Use of date.toJSON() Method to Convert a Date Object Into a String
  3. Example Codes: Use of date.toJSON() to Check the Difference in the Time Format of ISO Standard
JavaScript Date.toJSON() Method

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.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript Date