google-apps-script - Google 电子表格中的时区转换

标签 google-apps-script google-sheets timezone dst formulas

我知道这看起来很简单。

在 Google 电子表格中,我在一列中输入一个时区 (GMT) 的时间 另一列应该自动获取另一个时区的时间(太平洋时间)

 GMT      | PT
----------|------------
 5:00 AM  | 9:00 PM

到目前为止我正在使用

 =$C$3-time(8,0,0)

这里的问题是,我想更改夏令时的时间公式。

有没有可用的函数或脚本可以自动将夏令时纳入计算。

最佳答案

简短回答

没有内置函数,但您可以构建自定义函数。

示例

/**
 * Converts a datetime string to a datetime string in a targe timezone.
 *
 *@param {"October 29, 2016 1:00 PM CDT"} datetimeString Date, time and timezone.
 *@param {"Timezone"} timeZone Target timezone
 *@param {"YYYY-MM-dd hh:mm a z"} Datetime format
 *@customfunction
 */
function formatDate(datetimeString,timeZone,format) {
  var moment = new Date(datetimeString);
  if(moment instanceof Date && !isNaN(moment)){
    return Utilities.formatDate(moment, timeZone, format)
  } else {
    throw 'datetimeString can not be parsed as a JavaScript Date object'
  }
}

注意:

Google Apps 脚本中的

new Date(string)/Date.parse(string) 实现不支持某些时区缩写。

来自https://tc39.es/ecma262/#sec-date-time-string-format

There exists no international standard that specifies abbreviations for civil time zones like CET, EST, etc. and sometimes the same abbreviation is even used for two very different time zones.

相关

<小时/>

说明

为了考虑夏令时区,要转换的值的输入参数应包括日期,而不仅仅是一天中的时间。您可以设置默认日期和时区,通过在调用公式之前连接它来构建 datetimeString。

=formatDate("October 29, 2016 "&A2&" GMT","PDT","hh:mm a")

对于目标时区,除了三个字母缩写之外,我们还可以使用 TZ database names例如America/Los_Angeles,例如:

=formatDate("October 29, 2016 "&A2&" GMT","America/Los_Angeles","HH:mm")

如果时区缩写和 TZ 名称对于 datetimeString 使用时间偏移(即 UTC-4)失败。

另请参阅

引用文献

关于google-apps-script - Google 电子表格中的时区转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34946815/

相关文章:

google-apps-script - 谷歌表单中的 e.values 会跳过空答案,有解决方法吗?

javascript - 从客户端提供的时间戳(和时区)获取正确的时间

java - 关键云类型转换厂的时区变化

Google Sheets 脚本中的日期(持续时间)

javascript - Google Apps 脚本执行 API : Script error message: Script function not found:【JavaScript】

javascript - 将 JSON 响应转换为 Google Sheet(Google Apps 脚本)

google-apps-script - Google 表格 - 当文件名相同时,脚本为 “Replace” 而不是 “Create”

google-apps-script - 如何使用列标题引用 Google Apps 脚本电子表格中的单元格

javascript - Moment js默认时区在创建日期时不起作用

google-apps-script - GAS是否可以立即替换getActiveDocument()。getSelection()?