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

Javascript如何将星期序号转换为当周对应的具体日期

星期序号转当周具体日期实现方案(JavaScript)

核心实现代码

function convertWeekDaysToDates(availableDays, today = new Date()) {
  // 复制当前日期避免修改原日期对象
  const currentDate = new Date(today.getTime());
  // 获取当前日期对应星期序号(0=周日,6=周六)
  const currentWeekDay = currentDate.getDay();
  // 计算当周周日的基准日期
  const weekSunday = new Date(currentDate);
  weekSunday.setDate(currentDate.getDate() - currentWeekDay);

  // 遍历可用星期序号生成对应日期
  return availableDays.map(dayNum => {
    const targetDate = new Date(weekSunday);
    targetDate.setDate(weekSunday.getDate() + dayNum);
    // 格式化输出为 dd-mm-yyyy 格式
    const day = String(targetDate.getDate()).padStart(2, '0');
    const month = String(targetDate.getMonth() + 1).padStart(2, '0');
    const year = targetDate.getFullYear();
    return `${day}-${month}-${year}`;
  });
}

调用测试

const availableDays = [0,2,4,6];
const today = new Date('2021-08-20');
const output = convertWeekDaysToDates(availableDays, today);
console.log(output); // 输出结果:['15-08-2021', '17-08-2021', '19-08-2021', '21-08-2021']

逻辑说明

  • 以当周周日为基准日期,对应星期序号0的取值,其余序号直接在基准日期上叠加对应天数即可
  • 原生Date对象自动处理跨月、跨年的边界场景,无需额外判断
  • 可根据需求修改日期拼接规则,调整输出的日期格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:21:01