How to convert a date object's content into json in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

 date.toJSON()

The date.toJSON() is an inbuilt function in JavaScript which is used to convert the given date object’s contents into a string. The date object is created using date() constructor.

syntax

dateObj.toJSON();

This method doesn't take any parameters. It is just used along with the date object created and returns the converted string of Date() constructor contents.

Example-1

In the following example, using the date.toJSON() method, a date is converted into a string and the result is displayed in the output.

Live Demo

<html>
<body>
<script>
   var dateobj = new Date('October 19, 1993 05:35:32');
   var B = dateobj.toJSON();
   document.write(B + " " +"and its type is "+ typeof B);
</script>
</body>
</html>

Output

1993-10-19T00:05:32.000Z and its type is string


Example-2

In the following example, using the date.toJSON() method, several dates were converted into strings and the result is displayed in the output.

Live Demo

<html>
<body>
<script>
   var do1 = new Date('7');
   var do2 = new Date('9, 8');
   var do3 = new Date('4, 15, 19')
   var x = do1.toJSON();
   var y = do2.toJSON();
   var z = do3.toJSON();
   document.write(x);
   document.write("</br>");
   document.write(y);
   document.write("</br>");
   document.write(z);
</script>
</body>
</html>

Output

2001-06-30T18:30:00.000Z
2001-09-07T18:30:00.000Z
2019-04-14T18:30:00.000Z
raja
Published on 31-Jul-2019 14:46:55
Advertisements