ZapierJavaScript中的代码中的getHours和getUTCHours

问题描述

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

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

解决方法

下面的方法呢?如果约会伙伴总是这样。

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

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

,

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

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

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

我无法在Node.js中使语言环境在本地正常工作,但是对TZ来说却是正确的。

此处还有许多其他选项:Convert date to another timezone in JavaScript

,

以下是该问题的答案:

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