Home > Web Front-end > JS Tutorial > How to Format Dates with Timezone Offsets in ISO 8601 Using JavaScript?

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

Susan Sarandon
Release: 2024-12-04 00:28:09
Original
147 people have browsed it

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

ISO 8601 Formatting Dates with Timezone Offset in JavaScript

To efficiently format dates with timezone offsets in ISO 8601 format, leverage the following guidelines:

W3C Recommendation:

Consider the example: "2002-10-10T12:00:00−05:00". This signifies noon on October 10, 2002, accounting for the Central Daylight Savings Time (as well as Eastern Standard Time within the U.S.). Its equivalence in UTC is "2002-10-10T17:00:00Z," a five-hour difference.

Formatting Steps:

  1. Acquire Local Time: Utilize new Date() to obtain the local time. For instance, "var local = new Date().format("yyyy-MM-ddThh:mm:ss");" produces "2013-07-02T09:00:00".
  2. Calculate UTC Time Offset: Employ getTimezoneOffset() to determine the difference between the local time and UTC. For example, "var offset = local.getTimezoneOffset() / 60;" yields "7".
  3. Construct URL: Combine the local time and offset to form the URL's time component. "var duration = local "-" offset ":00";" produces "2013-07-02T09:00:00-7:00".

Handling Negative Timezone Offsets:

When getTimezoneOffset() returns negative values, such as "-120," the format should adhere to the following: "2013-07-02T09:00:00 12:00".

Helper Function:

This handy function simplifies ISO 8601 date formatting:

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);
}

var dt = new Date();
console.log(toIsoString(dt));
Copy after login

The above is the detailed content of How to Format Dates with Timezone Offsets in ISO 8601 Using 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template