J.O*_*sen 30 google-sheets google-apps-script
可以选择编写脚本并将其绑定到触发器.问题是,如何在脚本体中获取当前时间?
function myFunction() {
var currentTime = // <<???
}
Run Code Online (Sandbox Code Playgroud)
Jef*_*f B 47
使用JavaScript Date()
对象.有很多方法可以从对象中获取时间,日期,时间戳等.(参考)
function myFunction() {
var d = new Date();
var timeStamp = d.getTime(); // Number of ms since Jan 1, 1970
// OR:
var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance
}
Run Code Online (Sandbox Code Playgroud)
小智 9
我在我的谷歌文档中考虑了时区是这样的:
timezone = "GMT+" + new Date().getTimezoneOffset()/60
var date = Utilities.formatDate(new Date(), timezone, "yyyy-MM-dd HH:mm"); // "yyyy-MM-dd'T'HH:mm:ss'Z'"
Run Code Online (Sandbox Code Playgroud)
任何说在 Google Sheets 中获取当前时间并非 Google 脚本环境所独有的人显然从未使用过 Google Apps 脚本。
话虽这么说,你想返回当前时间吗?脚本用户的时区?脚本所有者的时区?
脚本时区由脚本所有者在脚本编辑器中设置。但是脚本的不同授权用户可以从File/Spreadsheet settings
Google Sheets 菜单中为他们使用的电子表格设置时区。
我猜你想要第一个选项。您可以使用内置函数获取电子表格时区,然后使用该类Utilities
来格式化日期。
var timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
var date = Utilities.formatDate(new Date(), SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "EEE, d MMM yyyy HH:mm")
Run Code Online (Sandbox Code Playgroud)
或者,使用 Javascript 的 date 方法获取相对于 UTC 时间的时区偏移量,格式化时区,并将其传递到Utilities.formatDate()
.
但这需要一个小的调整。run返回的偏移量getTimezoneOffset()
与我们通常对时区的看法相矛盾。如果偏移量为正,则本地时区落后于 UTC,就像美国时区一样。如果偏移量为负数,则本地时区早于 UTC,例如亚洲/曼谷、澳大利亚东部标准时间等。
const now = new Date();
// getTimezoneOffset returns the offset in minutes, so we have to divide it by 60 to get the hour offset.
const offset = now.getTimezoneOffset() / 60
// Change the sign of the offset and format it
const timeZone = "GMT+" + offset * (-1)
Logger.log(Utilities.formatDate(now, timeZone, 'EEE, d MMM yyyy HH:mm');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
96916 次 |
最近记录: |