Google Apps Script formatDate using user's time zone instead of GMT

Employee picture Employee · Sep 3, 2013 · Viewed 47k times · Source

I have a line that sets the current date and time in a cell:

sheet.getRange(1,1).setValue(new Date());

Then I have a line that creates a formatted date based on that cell's value:

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

The resulting addedTime seems to be in the GMT time zone and I need it to be in the user's time zone. It will usually be US Eastern Time (-0500), but if I simply subtract 5 hours from the time then that doesn't account for daylight saving time (-0400).

I checked the documentation for formatDate here: https://developers.google.com/apps-script/reference/utilities/utilities#formatDate(Date,String,String)

which links to the official Java SimpleDateFormat class documentation here: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

... but I can't find a list of valid time zones there to replace the GMT with.

Answer

Serge insas picture Serge insas · Sep 3, 2013

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