I’ve been struggling with setting date and times through automations. Since buttons and automations run on the server which works using UTC time, this creates problem if you are trying to set a date field based on some text/number input or to increment an existing date. I think the general advice has been to setup a variable to with the timezone offset and ensure that all local datetime is converted to UTC. However, when you are dealing with daylight saving, then the offsets can change.
Unfortunately, javascript doesn’t seem to have a default way of dealing with this. And you can’t load any third-party libraries in fibery scripts to take care of this for you (I wish that was possible).
I also looked at using an api. World Time API seems great for this. But they do mention that the api can be down from time to time so it is possible for this to fail. Nothing I’m doing is mission-critical but I would rather my automations don’t fail since there doesn’t seem to be a mechanism to tell them to wait and try again after a certain duration.
To get around all these issues, I created the following function. It is a hacky way of using core javascript date functions to convert a timezone db name (e.g. " America/New_York") into the current UTC offset:
// Function to calculate time zone offset
function getTZOffset(strTimeZone) {
//get current datetime in UTC
var dateUTC = new Date();
dateUTC.setUTCMilliseconds(0);
dateUTC.setSeconds(0);
//convert UTC datetime to particular timezone
const optionsLocal = {
timeZone: strTimeZone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: 'numeric',
minute: 'numeric',
hour12: false
};
var arrTZDate = dateUTC.toLocaleDateString('en-CA', optionsLocal).split(",");
var arrDate = arrTZDate[0].split("/").map(x => Number(x));
var arrTime = arrTZDate[1].split(":").map(x => Number(x));
var dateTZ = new Date(arrDate[2], arrDate[0] - 1, arrDate[1], arrTime[0], arrTime[1], 0, 0);
//calculate the time difference & return in hour offset
var tzDiff = dateTZ.getTime() - dateUTC.getTime();
return tzDiff / (60 * 60 * 1000);
}
This seems to work but I wonder if there is a more elegant way of dynamically finding the offset based on just the timezone name?
Thought I share this in case it is helpful to someone else and also see if there is any advice on how to improve this. I also thought that the fibery team might be persuaded to add a solid and mature date library and make it accessible to all so we don’t have to do crazy things like this.
I also wanted to again support @Matt_Blais 's request for centralized code library/reusable modules because maintaining all these helper functions all over the place is a nightmare.