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:
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
Output:
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
Output:
Explanation:
- The
Date
object is initialized with a specific date and time, andtoISOString()
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
Output:
Explanation:
- The
Date
object is set to 1,000,000 milliseconds after January 1, 1970 (Unix Epoch). toISOString()
returns the date1970-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.