如何使用脚本编辑器在Google电子表格中获取当前时间?

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 文档脚本


byt*_*gle 7

任何说在 Google Sheets 中获取当前时间并非 Google 脚本环境所独有的人显然从未使用过 Google Apps 脚本。

话虽这么说,你想返回当前时间吗?脚本用户的时区?脚本所有者的时区?

脚本时区由脚本所有者在脚本编辑器中设置。但是脚本的不同授权用户可以从File/Spreadsheet settingsGoogle 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)


Fra*_*ila 6

使用Datejavascript提供的对象.这对Google的脚本环境来说并不独特或特殊.