javascript Google Apps Script formatDate 使用用户的时区而不是 GMT
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18596933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google Apps Script formatDate using user's time zone instead of GMT
提问by Employee
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).
结果 addedTime 似乎在 GMT 时区,我需要它在用户的时区。它通常是美国东部时间 (-0500),但如果我只是从时间中减去 5 小时,那么这并没有考虑到夏令时 (-0400)。
I checked the documentation for formatDate here: https://developers.google.com/apps-script/reference/utilities/utilities#formatDate(Date,String,String)
我在这里检查了 formatDate 的文档: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
此处链接到官方 Java SimpleDateFormat 类文档: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.
...但我找不到有效时区列表来替换 GMT。
回答by Serge insas
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 :
但如果您想自己选择,Google Apps Script 会使用这些格式: