Anyone who says that getting the current time in Google Sheets is not unique to Google's scripting environment obviously has never used Google Apps Script.
That being said, do you want to return current time as to what? The script user's timezone? The script owner's timezone?
The script timezone is set in the Script Editor, by the script owner. But different authorized users of the script can set timezone for the spreadsheet they are using from File/Spreadsheet settings
menu of Google Sheets.
I guess you want the first option. You can use the built in function to get the spreadsheet timezone, and then use the Utilities
class to format date.
var timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
var date = Utilities.formatDate(new Date(), SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "EEE, d MMM yyyy HH:mm")
Alternatively, get the timezone offset from UTC time using Javascript's date method, format the timezone, and pass it into Utilities.formatDate()
.
This requires one minor adjustment though. The offset returned by getTimezoneOffset()
runs contradictory to how we often think of timezone. If the offset is positive, the local timezone is behind UTC, like US timezones. If the offset is negative, the local timezone is ahead UTC, like Asia/Bangkok, Australian Eastern Standard Time etc.
const now = new Date();
// getTimezoneOffset returns the offset in minutes, so we have to divide it by 60 to get the hour offset.
const offset = now.getTimezoneOffset() / 60
// Change the sign of the offset and format it
const timeZone = "GMT+" + offset * (-1)
Logger.log(Utilities.formatDate(now, timeZone, 'EEE, d MMM yyyy HH:mm');