JavaScript Date toJSON() method - JavaScript Tutorial

JavaScript Date toJSON() method

BLUF: This tutorial on JavaScript Date toJSON() method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript Date toJSON() method

Understanding JavaScript Date toJSON() method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience