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

如何让Google Apps Script识别Google Sheets中的日期为UTC时间?

解决Google Apps Script识别Slack UTC时间戳的问题

Slack返回的UTC时间字符串不带时区标识,导致Google Apps Script默认按本地时区解析,这是你遇到时间显示偏差的核心原因。下面是两种无需手动计算偏移量的简洁解决方法:

方法1:给UTC字符串追加时区标识

直接在Slack返回的UTC字符串末尾添加 UTC后缀,让脚本明确识别为UTC时间,再借助工具转换为EST/EDT:

// Slack返回的原始UTC时间字符串
const slackUtcStr = "Mon, 16 Oct 2023 13:07:42";
// 追加UTC时区标识,构建正确的UTC日期对象
const utcDate = new Date(slackUtcStr + " UTC");
// 转换为EST/EDT格式(自动处理夏令时切换)
const estEdtTime = Utilities.formatDate(utcDate, "America/New_York", "EEE, dd MMM yyyy HH:mm:ss");

// 写入Google Sheet指定单元格
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A1").setValue(estEdtTime);

方法2:用UTC方法直接构建日期

如果能从Slack的时间字符串中提取年、月、日、时、分、秒信息,可使用Date.UTC()直接创建UTC时间对象,再转换为目标时区:

// 从Slack字符串中提取的UTC时间组件(注意月份为0起始,10月对应9)
const year = 2023;
const month = 9;
const day = 16;
const hours = 13;
const minutes = 7;
const seconds = 42;

// 基于UTC组件创建日期对象
const utcDate = new Date(Date.UTC(year, month, day, hours, minutes, seconds));
// 转换为EST/EDT格式
const estEdtTime = Utilities.formatDate(utcDate, "America/New_York", "EEE, dd MMM yyyy HH:mm:ss");

// 写入表格
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A1").setValue(estEdtTime);

重要提示

使用Utilities.formatDate()并指定"America/New_York"时区时,脚本会自动处理EST(UTC-5)和EDT(UTC-4)的夏令时切换,无需手动调整偏移量,比硬编码毫秒数更可靠。

内容的提问来源于stack exchange,提问作者Joshua Pelton-Stroud

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:56:04