JavaScript Date toISOString()
Syntax & Examples


Date.toISOString() method

The toISOString() method of the Date object in JavaScript converts a date to a string following the ISO 8601 Extended Format. This method returns a string in simplified extended ISO format (YYYY-MM-DDTHH:mm:ss.sssZ) which is always 24 characters long.


Syntax of Date.toISOString()

The syntax of Date.toISOString() method is:

toISOString()

This toISOString() method of Date converts a date to a string following the ISO 8601 Extended Format.

Return Type

Date.toISOString() returns value of type String.



✐ Examples

1 Using toISOString() to get the ISO string of a Date object

In JavaScript, we can use the toISOString() method to get the ISO 8601 string of a Date object.

For example,

  1. We create a new Date object date representing January 1, 2000.
  2. We use the toISOString() method to get the ISO string of the date object.
  3. The ISO string is stored in the variable isoString.
  4. We log isoString to the console using console.log() method.

JavaScript Program

const date = new Date('2000-01-01T00:00:00Z');
const isoString = date.toISOString();
console.log(isoString);

Output

2000-01-01T00:00:00.000Z

2 Using toISOString() with a specific date

We can use the toISOString() method to get the ISO string of a specific Date object.

For example,

  1. We create a new Date object date representing July 4, 1776.
  2. We use the toISOString() method to get the ISO string of the date object.
  3. The ISO string is stored in the variable isoString.
  4. We log isoString to the console using console.log() method.

JavaScript Program

const date = new Date('1776-07-04T00:00:00Z');
const isoString = date.toISOString();
console.log(isoString);

Output

1776-07-04T00:00:00.000Z

3 Using toISOString() with the current date

We can use the toISOString() method to get the ISO string of the current date.

For example,

  1. We create a new Date object date representing the current date and time.
  2. We use the toISOString() method to get the ISO string of the date object.
  3. The ISO string is stored in the variable isoString.
  4. We log isoString to the console using console.log() method.

JavaScript Program

const date = new Date();
const isoString = date.toISOString();
console.log(isoString);

Output

Depends on the current date and time (e.g., '2024-05-27T12:34:56.789Z')

Summary

In this JavaScript tutorial, we learned about toISOString() method of Date: the syntax and few working examples with output and detailed explanation for each example.