JavaScript date.toISOString() method


The date.toISOString() method in JavaScript returns a string that represents the date and time in the ISO 8601 format (International Standard for date and time). This format is a widely used and precise representation of date and time.

Syntax:

date.toISOString();

Returns:

  • A string in the format: YYYY-MM-DDTHH:mm:ss.sssZ (e.g., "2024-10-22T10:30:15.123Z"), where:
    • YYYY is the year.
    • MM is the month (01-12).
    • DD is the day of the month (01-31).
    • T is the separator between the date and time.
    • HH is the hour (00-23).
    • mm is the minutes (00-59).
    • ss.sss is the seconds and milliseconds.
    • Z indicates the time is in UTC (Coordinated Universal Time).

Example 1: Getting the ISO 8601 String for the Current Date

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

Output:

2024-10-22T10:30:15.123Z

Explanation:

  • The toISOString() method converts the current date and time into the ISO 8601 format.
  • The time part is expressed in UTC, indicated by the Z at the end.

Example 2: ISO String for a Specific Date

const specificDate = new Date('December 17, 1995 03:24:00'); console.log(specificDate.toISOString());

Output:

1995-12-17T03:24:00.000Z

Explanation:

  • The Date object is initialized with a specific date and time, and toISOString() converts it into the ISO format. The time zone is adjusted to UTC, and the milliseconds are included as .000.

Example 3: Date with a Specific Milliseconds Value

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

Output:

1970-01-01T00:16:40.000Z

Explanation:

  • The Date object is set to 1,000,000 milliseconds after January 1, 1970 (Unix Epoch).
  • toISOString() returns the date 1970-01-01T00:16:40.000Z in the ISO format.

Summary:

  • date.toISOString() provides a precise and standardized representation of date and time in the ISO 8601 format.
  • The method always returns the date and time in UTC, regardless of the time zone of the original Date object.
  • This format is commonly used in APIs and data storage due to its unambiguous and globally accepted structure.