📌  相关文章
📜  在 Google Apps 脚本中获取时间 - Javascript (1)

📅  最后修改于: 2023-12-03 15:37:20.652000             🧑  作者: Mango

在 Google Apps 脚本中获取时间 - Javascript

Google Apps 脚本是一种可以用于扩展 Google 产品的脚本语言,同时也可以与其他 Google 服务集成。在 Google Apps 脚本中获取时间是一个常见需求,通常使用 Javascript 中的 Date 对象来实现。

获取当前时间

要获取当前时间,需要使用 Javascript 中的 Date 对象,它的构造函数可以不带参数创建一个当前时间对象,代码如下:

var now = new Date();

然后可以使用 Date 对象的方法来获取年月日时分秒等信息,例如:

var year = now.getFullYear();
var month = now.getMonth() + 1; // 月份从0开始,需要加1
var day = now.getDate();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
格式化时间

上面获取到的时间信息可以通过字符串拼接或使用字符串模板进行格式化输出,例如:

var formatted = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;

或者使用字符串模板的方式:

var formatted = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
其他常用操作

除了获取当前时间以外,还有其他一些常用的操作,例如:

比较时间

使用 Date 对象的 getTime() 方法可以将时间转换成毫秒数,毫秒数可以进行比较。

var date1 = new Date('2022-01-01');
var date2 = new Date('2022-01-02');
if (date2.getTime() > date1.getTime()) {
  // date2 大于 date1
}
时间加减

使用 Date 对象的 set 方法可以对时间进行加减操作,例如:

var date = new Date();
date.setMinutes(date.getMinutes() + 10); // 增加10分钟
date.setMonth(date.getMonth() - 1); // 减少1个月
总结

以上是在 Google Apps 脚本中获取时间的一些常见操作,主要使用了 Javascript 中的 Date 对象。在实际开发中,需要根据具体需求选择合适的方法来获取和处理时间。