Monday, 21 January 2019

Get script time zone for a date

The following Google Apps Script is a quick example of a recent improvement I have learned when handling dates (example blog post of the old method).

Rather than defining the timeZone as GMT (or GMT+1 for daylight savings) in the 'formatDate' property, I will be starting to use 'getScriptTimeZone' when it is not bound to a Google sheet. This eliminates the issue of the script becoming inaccurate by 1 hour when the clocks go back/forward, as it will pick up the time zone from when/where the script is being run.

function getScriptTimeZone() {
// get script time zone of location where being run
var timeZone = Session.getScriptTimeZone();
// create a new date variable
var newDate = new Date();
// format the new date variable as required
var niceDate = Utilities.formatDate(newDate, timeZone, "dd_MM_YYYY HH:mm:ss");
// log output
Logger.log(niceDate);
}
Get script time zone for a date.gs

No comments:

Post a Comment