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.
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.
In the following example, using the date.toJSON() method, a date is converted into a string and the result is displayed in the output.
<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>
1993-10-19T00:05:32.000Z and its type is string
In the following example, using the date.toJSON() method, several dates were converted into strings and the result is displayed in the output.
<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>
2001-06-30T18:30:00.000Z 2001-09-07T18:30:00.000Z 2019-04-14T18:30:00.000Z