Home > Web Front-end > JS Tutorial > How to Generate ISO 8601 Timestamps with Timezone Offset in JavaScript?

How to Generate ISO 8601 Timestamps with Timezone Offset in JavaScript?

DDD
Release: 2024-12-18 10:45:13
Original
144 people have browsed it

How to Generate ISO 8601 Timestamps with Timezone Offset in JavaScript?

ISO 8601 Formatting of Dates with Timezone Offset in JavaScript

Goal: Construct a URL with a timestamp in ISO 8601 format that includes the timezone offset.

Approach:

  1. Obtain the local time using new Date().
  2. Calculate the timezone offset from UTC using getTimezoneOffset().
  3. Construct the timestamp string in the required format: yyyy-MM-ddThh:mm:ss±hh:mm.

Implementation:

The following JavaScript function constructs the ISO 8601 timestamp:

function toIsoString(date) {
  var tzo = -date.getTimezoneOffset(),  // Negative offset means UTC is ahead of local time
      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);
}
Copy after login

For example, if the local time is 2013/07/02 9am and the timezone offset is -7 hours (UTC is 7 hours ahead):

var dt = new Date();
console.log(toIsoString(dt));  // Outputs: "2013-07-02T09:00:00-07:00"
Copy after login

Note that the or - sign indicates whether the local time is ahead of or behind UTC.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template