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

Apps Script中Utilities.formatDate处理时间格式化时区异常问题

问题原因分析

你遇到的问题核心在于:new Date(end - start) 创建的是基于UTC纪元(1970年1月1日00:00:00 UTC)加上时间差的日期对象。你的时区是GMT-6,UTC时间的00:00:08转换到GMT-6时区后,对应的是前一天的18:00:08(12小时制下显示为06:00:08),这就是多余6小时的来源。

解决方案

不需要复杂的变量计算,直接用两种方式解决:

方式一:使用UTC时区格式化时间差

既然时间差是基于UTC纪元的偏移量,直接指定时区为'UTC'即可得到正确的时间差:

function sleepTime() {
  var start = new Date();
  console.log('Start: ' + Utilities.formatDate(start, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), 'hh:mm:ss'));

  Utilities.sleep(8000);

  var end = new Date();
  console.log('End: ' + Utilities.formatDate(end, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), 'hh:mm:ss'));

  var processTime = new Date(end - start);
  // 这里将时区改为UTC
  console.log('Processing time : ' + Utilities.formatDate(processTime, 'UTC', 'hh:mm:ss'));
}

执行后会输出Processing time : 00:00:08,符合预期。

方式二:直接计算时间差的时分秒

如果不想依赖时区,也可以直接对毫秒差进行计算:

function sleepTime() {
  var start = new Date();
  console.log('Start: ' + Utilities.formatDate(start, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), 'hh:mm:ss'));

  Utilities.sleep(8000);

  var end = new Date();
  console.log('End: ' + Utilities.formatDate(end, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), 'hh:mm:ss'));

  var diffMs = end - start;
  var hours = Math.floor(diffMs / (1000 * 60 * 60));
  var minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((diffMs % (1000 * 60)) / 1000);
  // 补零格式化
  var processTimeStr = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  console.log('Processing time : ' + processTimeStr);
}

这种方式也能得到00:00:08的正确结果,且不受时区影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 18:05:03