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

假装没事ソ 提交于 2019-11-26 21:33:38

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/18596933/google-apps-script-formatdate-using-users-time-zone-instead-of-gmt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!