25

In a function within Google Apps Script I am using Utilities.formatDate()

let formattedTimestamp = Utilities.formatDate(new Date(), "GMT", "hh:mm a");

The resulting string is a timestamp in the GMT time zone but I need it to be in the current user's time zone, and account for daylight saving time.

The documentation links to the Java SimpleDateFormat class documentation but I can't find a list of valid time zones with which I'd replace GMT.

Employee
  • 2,231
  • 3
  • 33
  • 60

1 Answers1

53

You can directly get the spreadsheet Time Zone like this :

  var addedDate = sheet.getRange(1,1).getValue();
  var addedTime = Utilities.formatDate(addedDate, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "hh:mm a");

See doc here

but Google Apps Script uses these formats if you want to choose it yourself :

http://joda-time.sourceforge.net/timezones.html

Serge insas
  • 45,904
  • 7
  • 105
  • 131
  • 5
    Update: `Session.getScriptTimeZone()` also worked for my needs. https://developers.google.com/apps-script/reference/base/session – Employee Jul 11 '17 at 15:24
  • 9
    @mike: One potential problem with using `Session.getScriptTimeZone()` is if you deploy the script across timezones. Your end-user in a different tz will end up with timestamps synced to the script's tz rather than the spreadsheet's tz. – Dean Ransevycz Sep 14 '17 at 23:14