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

Google Apps Script工作日计算:如何替换已弃用的getDay等方法?

替换Google Sheets脚本中日期方法的方案

首先需要澄清:标准JavaScript的getDay()、getDate()、setDate()并未被弃用,仍可在Google Apps Script中正常使用。如果是出于追求更现代、健壮的日期处理方式,或是误看到过时文档提示,可采用以下两种替代方案:

方案1:使用Temporal API(现代日期处理标准)

Google Apps Script现已支持ECMAScript的Temporal API,它提供了更清晰、无副作用的日期操作方式:

function getWorkingDays(startDate, endDate) {
  const days = [];
  // 将输入的Date对象转换为Temporal.PlainDate(无时区的日期对象)
  let currentDate = Temporal.PlainDate.from(startDate);
  const endPlainDate = Temporal.PlainDate.from(endDate);

  // 比较当前日期是否小于等于结束日期
  while (currentDate.compare(endPlainDate) <= 0) {
    // Temporal的dayOfWeek属性返回1(周一)至7(周日)
    const dayOfWeek = currentDate.dayOfWeek;
    // 排除周六(6)和周日(7)
    if (dayOfWeek !== 6 && dayOfWeek !== 7) {
      // 转换回Date对象适配Google Sheets的使用场景
      days.push(currentDate.toDate());
    }
    // 安全地增加一天(不会修改原对象)
    currentDate = currentDate.add({ days: 1 });
  }
  return days;
}

方案2:通过时间戳操作替代日期方法

若不想引入Temporal API,可通过操作时间戳(毫秒数)来实现相同逻辑,避免直接调用setDate():

function getWorkingDays(startDate, endDate) {
  const days = [];
  const oneDayMs = 24 * 60 * 60 * 1000; // 一天对应的毫秒数
  let currentTimestamp = startDate.getTime();
  const endTimestamp = endDate.getTime();

  while (currentTimestamp <= endTimestamp) {
    const currentDate = new Date(currentTimestamp);
    // 保留原逻辑的getDay()判断(0=周日,6=周六)
    const dayOfWeek = currentDate.getDay();
    if (dayOfWeek !== 0 && dayOfWeek !== 6) {
      days.push(new Date(currentTimestamp));
    }
    // 递增时间戳来推进日期
    currentTimestamp += oneDayMs;
  }
  return days;
}

补充说明

原脚本中的getDay()、getDate()、setDate()方法目前在Google Apps Script中完全可用,不存在官方弃用情况。如果之前看到弃用提示,大概率是混淆了Google Apps Script早期的旧版专属API(而非标准JS的Date方法)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 07:55:30