JavaScript Date toJSON() method



The JavaScript Date.toJSON() method is used to convert a Date object into a string representing the given date in the date time JSON string format according to universal time. If the Date object is Invalid Date, then this method returns "null" as result. Additionally, this method does not accept any parameters.

Syntax

Following is the syntax of JavaScript Date toJSON() method −

toJSON();

This method does not accept any parameters.

Return Value

A string representing the given date in the date time string format according to universal time.

Example 1

In the following example, we are using the JavaScript toJSON() method to convert the current date and time into a JSON-formatted string.

<html>
<body>
<script>
   const currentDate = new Date();
   const jsonDate = currentDate.toJSON();

   document.write(jsonDate);
</script>
</body>
</html>

Output

As we can see the output, this method returns a formatted JSON string.

Example 2

Here, we are creating a date object with a specific date and time "2023-12-31T08:15:30" −

<html>
<body>
<script>
   const customDate = new Date('2023-12-31T08:15:30');
   const jsonCustomDate = customDate.toJSON();

   document.write(jsonCustomDate);
</script>
</body>
</html>

Output

The program converts the specific date and time into a formatted JSON string.

Example 3

Here, we provided the date value as "50" which is out of range.

<html>
<body>
<script>
   const currentDate = new Date('2023-12-50T05:06:01.516Z');
   const jsonDate = currentDate.toJSON();

   document.write(jsonDate);
</script>
</body>
</html>

Output

If we execute the program, "null" will be returned as output.

Example 4

In the following example, we are adding 10 days to the date object and converting the modified date to a JSON-formatted string.

<html>
<body>
<script>
   const futureDate = new Date();
   futureDate.setDate(futureDate.getDate() + 10);

   const jsonFutureDate = futureDate.toJSON();

   document.write(jsonFutureDate);
</script>
</body>
</html>

Output

The result will be a string representing the date and time 10 days in the future.

Advertisements