0

In a Code by Zapier task, how to I get the local time of a date/time provided in UTC. I am in time zone Europe/London. At the time of posting, owing to daylight saving, 9 AM London time is 8 AM UTC. But the following both return 8 when used in a Code by Zapier task.

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

3 Answers3

0

What about below method? If date formate is always like that.

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

+ used to convert the result to number;

AMD
  • 163
  • 1
  • 10
  • Thank you Ahmad. You're right, that works if my variable is a string. But my variable is a date/time. I have edited my question to set this out better. – colinp_1 Sep 02 '20 at 02:47
0

Zapier code is run in AWS Lambda, where the local time is always UTC.

You can use the JS toLocaleString to convert to your local timezone.

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

I wasn't able to get the locale working correctly locally in Node.js, but it does to the TZ correctly.

Lots of other options here: Convert date to another timezone in JavaScript

xavdid
  • 5,092
  • 3
  • 20
  • 32
0

Here is an answer to the question:

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

See discussion here: https://community.zapier.com/ask-the-community-3/gethours-and-getutchours-in-code-by-zapier-javascript-4734?postid=17229#post17229

colinp_1
  • 3
  • 5