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

Angular+Express课程管理API:如何获取指定时间段内对应周几的所有日期

解决方案

原生JavaScript/TypeScript没有直接匹配该需求的内置函数,你可以基于标准Date对象的API实现,Angular和Node.js Express环境均可通用。

实现思路

  • 先将输入的开始、结束日期字符串转为标准Date对象,同时将传入的星期几参数转换为0-6的数值(注:JS原生Date.getDay()返回值规则为周日=0、周一=1、周六=6,需和你传入的参数规则做对应适配)
  • 计算开始日期之后第一个符合目标星期几的日期:先取开始日期的周几数值,计算和目标周几的差值,差值为负则加7得到偏移天数,开始日期加该偏移天数即为第一个符合要求的日期
  • 后续每次给当前目标日期加7天,判断是否小于等于结束日期,符合则推入结果数组,直到日期超出结束范围为止

通用实现代码

/**
 * 获取指定日期范围内所有对应星期几的日期集合
 * @param startDateStr 开始日期,支持YYYY-MM-DD/YYYY/MM/DD等标准日期格式
 * @param endDateStr 结束日期,格式要求同上
 * @param targetWeekDay 目标星期几,取值0-6,0=周日、1=周一...6=周六
 * @param format 返回日期的格式,默认d.M.yyyy对应示例中的4.1.2021格式
 * @returns 格式化后的日期数组
 */
function getWeekDaysInRange(
  startDateStr: string,
  endDateStr: string,
  targetWeekDay: number,
  format: string = 'd.M.yyyy'
): string[] {
  const result: string[] = []
  const startDate = new Date(startDateStr)
  const endDate = new Date(endDateStr)
  // 统一设置时间避免时区导致的日期偏差
  startDate.setHours(0, 0, 0, 0)
  endDate.setHours(23, 59, 59, 999)

  // 计算第一个目标周几的日期偏移量
  const startDay = startDate.getDay()
  let diff = targetWeekDay - startDay
  if (diff < 0) diff += 7
  let currentDate = new Date(startDate)
  currentDate.setDate(startDate.getDate() + diff)

  // 循环累加7天直到超出结束日期
  while (currentDate <= endDate) {
    // 按要求格式化日期
    const formattedDate = format
      .replace('yyyy', currentDate.getFullYear().toString())
      .replace('M', (currentDate.getMonth() + 1).toString())
      .replace('d', currentDate.getDate().toString())
    result.push(formattedDate)
    // 日期加7天
    currentDate.setDate(currentDate.getDate() + 7)
  }
  return result
}

调用示例

匹配你给出的测试场景,调用方式如下:

// 查询2021/1/1到2021/1/30范围内的所有周一(周一对应targetWeekDay=1)
const courseMondays = getWeekDaysInRange('2021/1/1', '2021/1/30', 1)
console.log(courseMondays) // 输出:["4.1.2021", "11.1.2021", "18.1.2021", "25.1.2021"]

优化建议

如果项目中已经引入dayjs或date-fns这类轻量日期工具库,可以直接使用库提供的日期偏移、格式化方法,无需自己处理时区和格式化逻辑,代码健壮性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 10:27:03