【问题标题】:getHours() and getUTCHours in Code by Zapier (JavaScript)Zapier (JavaScript) 的代码中的 getHours() 和 getUTCHours
【发布时间】:2020-12-21 00:13:47
【问题描述】:

在 Zapier 任务的代码中,如何获取以 UTC 提供的日期/时间的本地时间。我在欧洲/伦敦时区。在发布时,由于夏令时,伦敦时间上午 9 点是 UTC 时间上午 8 点。但在 Zapier 任务的代码中使用时,以下两者都返回 8。

var myDateTime = new Date("2020-09-01T08:00:00.000Z");
var localHours = myDateTime.getHours(); // returns 8
var utcHours = myDateTime.getUTCHours(); // returns 8

【问题讨论】:

    标签: javascript utc dst zapier


    【解决方案1】:

    下面的方法呢?如果日期格式总是这样。

    +'2020-09-01T09:00:00.000+01:00'.split('T')[1].slice(0,2); // 9
    

    + 用于将结果转换为数字;

    【讨论】:

    • 谢谢艾哈迈德。你是对的,如果我的变量是一个字符串,那就有效。但我的变量是日期/时间。我已经编辑了我的问题以更好地说明这一点。
    【解决方案2】:

    Zapier 代码在 AWS Lambda 中运行,本地时间始终为 UTC。

    您可以使用 JS toLocaleString 转换为您当地的时区。

    new Date().toLocaleString('en-GB', {timeZone: 'Europe/London'})
    

    我无法让本地环境在 Node.js 中正常工作,但它对 TZ 正确。

    这里还有很多其他选项:Convert date to another timezone in JavaScript

    【讨论】:

      【解决方案3】:

      这是问题的答案:

      function getLocalDatetime(utcDatetime, timeZone) {
        const dt = new Date(utcDatetime).toLocaleString("en-US", { timeZone });
        return new Date(dt);
      }
      
      const myUTCDatetime = new Date("2020-09-01T08:00:00.000Z");
      const myLocalDatetime = getLocalDatetime(myUTCDatetime, "Europe/London");
      const utcHours = myUTCDatetime.getHours();
      const localHours = myLocalDatetime.getHours();
      
      return {
        myUTCDatetime: myUTCDatetime,
        myLocalDatetime: myLocalDatetime,
        utcHours: utcHours,
        localHours: localHours
      };
      

      在此处查看讨论:https://community.zapier.com/ask-the-community-3/gethours-and-getutchours-in-code-by-zapier-javascript-4734?postid=17229#post17229

      【讨论】:

        猜你喜欢
        • 2019-08-15
        • 1970-01-01
        • 2018-07-04
        • 2020-02-19
        • 2010-10-28
        • 2017-12-06
        • 2022-01-15
        • 2017-06-09
        • 2016-12-27
        相关资源
        最近更新 更多