You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修正Google Apps Script中全天日历事件日期偏移问题?

解决Google Apps Script中全天日历事件日期偏移问题

问题根源在于getAllDayStartDate()返回的是UTC标准时间,而你的日历时区为GMT+1(UTC+1)。全天事件的本地开始时间是当日00:00,对应UTC时间的前一天23:00,因此直接返回的Date对象会显示为前一天的时间。

以下两种方案可以在脚本中直接返回正确日期:

方案1:格式化日期为本地时区字符串(推荐)

使用Utilities.formatDate()将UTC时间转换为对应时区的日期字符串,彻底避免时区混淆:

修改循环内的对象创建代码:

// 获取日历的时区设置(替代硬编码的GMT+1,适配任意时区)
var calendarTimeZone = cal.getTimeZone();

for(var item of items)
{
  var obj = {
    TYPE: item.getTitle(),
    DATE: Utilities.formatDate(item.getAllDayStartDate(), calendarTimeZone, "yyyy-MM-dd")
  };
  arr.push(obj);
  if(++itemCount >= 10) {
    break;
  }
}

该方法直接返回yyyy-MM-dd格式的日期字符串,比如全天事件是5月20日,就会返回"2024-05-20",完全符合预期。

方案2:调整Date对象的时区偏移

如果需要返回Date对象而非字符串,可以手动添加时区偏移量(GMT+1对应3600000毫秒):

for(var item of items)
{
  var utcStartDate = item.getAllDayStartDate();
  // 添加1小时偏移,转换为本地时区的Date对象
  var localStartDate = new Date(utcStartDate.getTime() + 3600000);
  var obj = {
    TYPE: item.getTitle(),
    DATE: localStartDate
  };
  arr.push(obj);
  if(++itemCount >= 10) {
    break;
  }
}

注意:Date对象在日志中仍会显示UTC时间,但日期部分已修正为本地时区的正确日期。

内容的提问来源于stack exchange,提问作者Gilbert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 05:43:28