JavaScript Date toISOString() Method



The JavaScript Date.toISOString() method is used to convert the Date object as a string in a standardized format known as ISO 8601.

ISO 8601 stands for "International Organization for Standardization" and it is an international standard for representing dates and times. The primary goal of ISO 8601 is to provide a standardized way to represent dates and times, making it easier to exchange and interpret information globally.

The format of ISO 8601 is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or YYYYYY-MM-DDTHH:mm:ss.sssZ).

Syntax

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

toISOString();

This method does not accept any parameters.

Return Value

This method returns a string representing the given Date object in ISO 8601 format.

Example 1

Following is the basic usage of JavaScript Date toISOString() method −

<html>
<body>
<script>
   const date = new Date();
   document.write(date.toString(), "<br>"); //returns date object as string

   document.write(date.toISOString()); //returns date object as string, using ISO 8601 format
</script>
</body>
</html>

Output

After executing, the program shows the difference between toString() and toISOString() methods.

Example 2

In the following example, we are creating a Date object for a specific date and time, then converting it to a string in the ISO 8601 format.

<html>
<body>
<script>
   const specificDate = new Date('2023-10-31T12:45:00');
   const isoString = specificDate.toISOString();

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

Output

The above program returns "2023-10-31T07:15:00.000Z" as result.

Example 3

If the date of the Date object is invalid, this method cannot represent it in the date string format −

<html>
<body>
<script>
   const specificDate = new Date('2023287-10-31T12:45:00');
   const isoString = specificDate.toISOString();

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

Output

As we can see in the output, it didn't returned the Date object in date string format.

Advertisements