如何在 JavaScript 中使用 ISO 8601 格式化带有时区偏移的日期?

2022-01-16 00:00:00 timezone javascript date-formatting

目标:找到本地时间UTC时间偏移,然后构造如下格式的URL.

Goal: Find the local time and UTC time offset then construct the URL in following format.

示例网址:/Actions/Sleep?duration=2002-10-10T12:00:00−05:00

格式基于W3C 推荐.文档说:

例如,2002-10-10T12:00:00−05:00(2002 年 10 月 10 日中午,美国中部夏令时和东部标准时间)等于 2002-10-10T17:00:00Z,比 2002-10-10T12:00:00Z 晚五个小时.

For example, 2002-10-10T12:00:00−05:00 (noon on 10 October 2002, Central Daylight Savings Time as well as Eastern Standard Time in the U.S.) is equal to 2002-10-10T17:00:00Z, five hours later than 2002-10-10T12:00:00Z.

所以根据我的理解,我需要通过 new Date() 找到我的当地时间,然后使用 getTimezoneOffset() 函数计算差异,然后将其附加到字符串结束.

So based on my understanding, I need to find my local time by new Date() then use getTimezoneOffset() function to compute the difference then attach it to the end of string.

  1. 使用格式

var local = new Date().format("yyyy-MM-ddThh:mm:ss"); // 2013-07-02T09:00:00

  • 按小时获取 UTC 时间偏移量

  • Get UTC time offset by hour

    var offset = local.getTimezoneOffset() / 60; // 7
    

  • 构造 URL(仅限时间部分)

  • Construct URL (time part only)

    var duration = local + "-" + offset + ":00"; // 2013-07-02T09:00:00-7:00
    

  • 以上输出表示我的当地时间是 2013/07/02 上午 9 点,与 UTC 的差异是 7 小时(UTC 比当地时间早 7 小时)

    The above output means my local time is 2013/07/02 9am and difference from UTC is 7 hours (UTC is 7 hours ahead of local time)

    到目前为止,它似乎有效,但如果 getTimezoneOffset() 返回负值,如 -120?

    So far it seems to work but what if getTimezoneOffset() returns negative value like -120?

    我想知道在这种情况下格式应该是什么样子,因为我无法从 W3C 文档中弄清楚.

    I'm wondering how the format should look like in such case because I cannot figure out from W3C documentation.

    推荐答案

    这是一个简单的帮助函数,它将为您格式化 JS 日期.

    Here's a simple helper function that will format JS dates for you.

    function toIsoString(date) {
      var tzo = -date.getTimezoneOffset(),
          dif = tzo >= 0 ? '+' : '-',
          pad = function(num) {
              var norm = Math.floor(Math.abs(num));
              return (norm < 10 ? '0' : '') + norm;
          };
    
      return date.getFullYear() +
          '-' + pad(date.getMonth() + 1) +
          '-' + pad(date.getDate()) +
          'T' + pad(date.getHours()) +
          ':' + pad(date.getMinutes()) +
          ':' + pad(date.getSeconds()) +
          dif + pad(tzo / 60) +
          ':' + pad(tzo % 60);
    }
    
    var dt = new Date();
    console.log(toIsoString(dt));

    相关文章