Home >Web Front-end >JS Tutorial >How to Format a JavaScript Date in ISO 8601 with Timezone Offset?

How to Format a JavaScript Date in ISO 8601 with Timezone Offset?

Linda Hamilton
Linda HamiltonOriginal
2024-11-28 12:28:11310browse

How to Format a JavaScript Date in ISO 8601 with Timezone Offset?

ISO 8601 Formatting of Date with Timezone Offset in JavaScript

This article addresses the common issue of how to format a JS date in the ISO 8601 format with an offset from UTC. It starts by discussing the goal of formatting the URL in the correct format, based on the W3C recommendation.

The solution involves a series of steps:

  1. Getting the local time: The new Date() function is used to obtain the local time in the desired format (e.g., "yyyy-MM-ddThh:mm:ss").
  2. Calculating UTC time offset: The getTimezoneOffset() method is called to compute the difference between local time and UTC. The result is then divided by 60 to express the offset in hours.
  3. Constructing the URL: The local time and the calculated UTC offset are combined to form the duration string, which represents the desired ISO 8601 formatted date with timezone offset (e.g., "2013-07-02T09:00:00-7:00").

However, the question arises as to how to handle negative values for getTimezoneOffset(). The provided answer utilizes a helper function to address this:

function toIsoString(date) {
  var tzo = -date.getTimezoneOffset(),
      dif = tzo >= 0 ? '+' : '-',
      pad = function(num) {
          return (num < 10 ? '0' : '') + num;
      };

  return date.getFullYear() +
      '-' + pad(date.getMonth() + 1) +
      '-' + pad(date.getDate()) +
      'T' + pad(date.getHours()) +
      ':' + pad(date.getMinutes()) +
      ':' + pad(date.getSeconds()) +
      dif + pad(Math.floor(Math.abs(tzo) / 60)) +
      ':' + pad(Math.abs(tzo) % 60);
}

This helper function takes a date as an argument and returns a properly formatted ISO 8601 string, including the timezone offset.

The above is the detailed content of How to Format a JavaScript Date in ISO 8601 with Timezone Offset?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn