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

TypeScript添加extraday计算日期时如何正确排除周六周日

日期排除周末逻辑修正方案

问题背景

现有逻辑可实现排除周六、周日,将剩余符合要求的日期推入数组。新增extraday额外天数配置后,要求该场景下同样排除周六周日,但实际运行时周末日期仍被纳入结果,需要调整逻辑让extraday对应的日期取值正确过滤周末。
原问题代码:

const extraday:number=3;
for (let i = 1 + extraday; i <= 15 + extraday; i++) {
  const dt = new Date();
  dt.setDate(dt.getDate() + i);
  if (dt.getDay() !== 6 && dt.getDay() !== 0) {// excluding weekends
    Array.push(); //
  }
}

问题原因

原代码有两个核心问题导致结果不符合预期:

  • 循环按固定15个自然日跨度遍历,遇到周末不会自动顺延,extraday的偏移量是按自然日计算而非工作日计算,偏移落点如果跨周末很容易和预期的工作日偏移结果不符
  • Array.push()写法错误,没有传入待存入的日期对象,也没有指定自定义的目标数组,本身无法正确存储结果

修正实现

根据业务需求分两种场景调整:

场景1:要求extraday和后续15天都按工作日计算(周末完全跳过,最终固定返回15个工作日)

不要用固定自然日步长循环,改为逐天遍历校验,每遇到周末就跳过不计数,直到收满要求数量的工作日为止:

const extraday: number = 3;
const targetDates: Date[] = [];
// 初始化到extraday偏移的起始基准日期
const currentDate = new Date();
currentDate.setDate(currentDate.getDate() + extraday);
let workDayCount = 0;

while (workDayCount < 15) {
  // 逐天往后偏移
  currentDate.setDate(currentDate.getDate() + 1);
  const day = currentDate.getDay();
  // 过滤周六(6)、周日(0)
  if (day !== 0 && day !== 6) {
    // 存入新的日期副本,避免引用复用导致所有数组元素值一致
    targetDates.push(new Date(currentDate));
    workDayCount++;
  }
}

场景2:要求按自然日偏移extraday后,在接下来15个自然日范围内筛选工作日(返回结果数量不固定)

原日期判断逻辑本身没有问题,只需要修正push的写法即可:

const extraday: number = 3;
const targetDates: Date[] = [];
for (let i = 1 + extraday; i <= 15 + extraday; i++) {
  const dt = new Date();
  dt.setDate(dt.getDate() + i);
  const day = dt.getDay();
  if (day !== 6 && day !== 0) {
    targetDates.push(new Date(dt));
  }
}

注意:场景2的实现因为是在固定自然日窗口内筛选,跨周末时最终返回的工作日数量通常为10-13个,无法固定凑满15个,按需选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 06:51:37