"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Generate ISO 8601 Format Dates with Timezone Offsets in JavaScript?

How to Generate ISO 8601 Format Dates with Timezone Offsets in JavaScript?

Published on 2024-12-23
Browse:569

How to Generate ISO 8601 Format Dates with Timezone Offsets in JavaScript?

ISO 8601 Format Dates with Timezone Offset in JavaScript

In JavaScript, constructing dates in ISO 8601 format with timezone offset can be challenging due to potential negative timezone offsets. This article addresses this issue and provides a solution.

Understanding the Format

The ISO 8601 format specifies dates as follows: YYYY-MM-DDThh:mm:ss±hh:mm. For example, 2002-10-10T12:00:00-05:00 represents noon on October 10, 2002, in Central Daylight Savings Time (five hours behind UTC).

Finding Local Time and UTC Offset

To construct the ISO 8601 string, we must first obtain the local time using new Date() and calculate the UTC offset using getTimezoneOffset(). The offset is obtained in minutes, so we divide it by 60 to get the number of hours.

Handling Negative Timezone Offsets

The getTimezoneOffset() function can return negative values. In such cases, we must format the offset differently. For example, an offset of -120 minutes should be displayed as 02:00 (two hours ahead of UTC).

Helper Function for Formatting

To simplify the process, a helper function, toIsoString, can be utilized to format dates in ISO 8601 format with timezone offsets:

function toIsoString(date) {
  var tzo = -date.getTimezoneOffset(), // Make the offset positive
      dif = tzo >= 0 ? ' ' : '-', // Determine the sign
      pad = function(num) { // Ensure two-digit representation
          return (num 

This function takes a date as an argument and formats it according to the ISO 8601 specification, including the timezone offset.

Example Usage

The following code demonstrates how to use the toIsoString function:

var dt = new Date();
console.log(toIsoString(dt)); // Outputs the date in ISO 8601 format with timezone offset

Using this approach, you can easily format dates in JavaScript according to the ISO 8601 standard, ensuring that they adhere to the proper format.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3