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

如何使用Google Apps Script重新格式化二维数组中的日期?

我有以下代码,想要把每个内层数组的第一个元素也就是日期重新格式化,通过Google Apps Script得到指定格式的输出结果,请问应该怎么实现?

function test() {
  const input = [['Fri Oct 15 2021 00:00:00 GMT-0400 (Eastern Daylight Time)', 123.19],
  ['Thu Oct 14 2021 00:00:00 GMT-0400 (Eastern Daylight Time)', 122.83]];

  // 这里的代码要怎么修改,才能把每个内层数组的日期格式化得到如下输出
  var output = input.map(el => el);
  // 预期输出:
  // output = [['Oct 15, 2021', 123.19],
  // ['Oct 14, 2021', 122.83]];
}

实现方案

推荐使用Google Apps Script内置的Utilities.formatDate()方法实现,该方法支持自定义时区,能避免原生JS日期方法的时区偏移问题,修改后的完整代码如下:

function test() {
  const input = [
    ['Fri Oct 15 2021 00:00:00 GMT-0400 (Eastern Daylight Time)', 123.19],
    ['Thu Oct 14 2021 00:00:00 GMT-0400 (Eastern Daylight Time)', 122.83]
  ];

  const output = input.map(el => {
    // 将原始字符串转为日期对象
    const rawDate = new Date(el[0]);
    // 按指定时区和格式输出日期
    const formattedDate = Utilities.formatDate(rawDate, "America/New_York", "MMM dd, yyyy");
    return [formattedDate, el[1]];
  });

  console.log(output);
}

如果不需要严格匹配原始的东部时区,也可以用原生JS方法实现,无需调用GAS内置接口:

const output = input.map(el => {
  const rawDate = new Date(el[0]);
  const formattedDate = rawDate.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric'
  })
  return [formattedDate, el[1]]
})
  • 格式符说明:MMM对应月份短写(Oct/Jan等),dd对应两位日期,yyyy对应四位年份,可根据需求调整格式组合。
  • 时区参数可以根据实际场景替换,中国大陆地区可填写Asia/Shanghai。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:06:03