JavaScript Date toJSON() method

The toJSON method in JavaScript for Date objects converts the given date into a string format. This method is utilized to serialize Date instances when performing JSON serialization.

Syntax

The syntax for the toJSON method is depicted as follows:

Example

dateObj.toJSON()

Return

A string representing the specified date.

JavaScript Date toJSON method example

In this section, we will explore the toJSON method by examining a range of examples.

Example 1

Let’s examine an example that retrieves the current date formatted as a string.

Example

<script>

var date=new Date();

document.writeln(date.toJSON());

</script>

Output:

Output

2018-08-09T12:25:35.824Z

Example 2

Let’s explore another illustration of how to retrieve the current date represented as a string.

Example

<script>

var date=new Date();

var jsonDate=date.toJSON();

document.writeln(new Date(jsonDate).toUTCString());

</script>

Output:

Output

Thu, 09 Aug 2018 12:40:55 GMT

Example 3

Let’s examine an example that demonstrates how to transform a given Date object into a string format.

Example

<script>

var date=new Date(1947, 7, 15, 20, 22, 10);

document.writeln(date.toJSON());

</script>

Output:

Output

1947-08-15T14:52:10.000Z

Input Required

This code uses input(). Please provide values below: