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

Google Sheets App Script中API返回大时间戳转换为指定日期格式问题求助

解决方案

你拿到的API返回的时间戳是纳秒级时间戳,而Utilities.formatDate方法要求传入的时间参数是毫秒级时间戳或者Date对象,直接传入纳秒值会超出正常时间范围,自然得不到正确结果。

你可以参考以下代码实现转换:

function convertNanoTimestamps() {
  // 你从API拿到的原始二维数组
  const rawTimestamps = [[1.6370611672429312E18], [1.63706107263277082E18], [1.63706100204943616E18], [1.63706094340754534E18], [1.63706078474499994E18], [1.63706064715950106E18], [1.63706061367677235E18], [1.63706061367677082E18], [1.63706061367676902E18], [1.63706061367676749E18], [1.63706061367676595E18], [1.63706061367676442E18]];
  // 转换后的日期数组
  const convertedDates = rawTimestamps.map(row => {
    // 纳秒转毫秒:除以1e6后取整避免小数问题
    const msTimestamp = Math.round(row[0] / 1000000);
    // 按要求格式输出,时区可按需修改第二个参数
    return Utilities.formatDate(new Date(msTimestamp), "GMT", "MM/dd/yyyy HH:mm");
  });
  // 如需直接写入Google Sheets,可取消注释下一行,示例为写入当前激活工作表的A列
  // SpreadsheetApp.getActiveSheet().getRange(1,1,convertedDates.length,1).setValues(convertedDates.map(d => [d]));
  return convertedDates;
}

注意事项

  • 如果你需要使用其他时区,把Utilities.formatDate的第二个参数替换为对应时区ID即可,比如东八区可填Asia/Shanghai
  • 该转换逻辑仅适配当前纳秒级精度的时间戳,若后续API返回的时间戳精度变更,可对应调整换算系数:微秒级除以1e3,秒级乘以1e3即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:45:05