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

基于new Date生成未来60天各星期几对应时段数组的技术需求

生成未来60天内按星期几分组的时段数组

实现思路

  • 先定义各工作日的时段规则,用Date.getDay()的返回值(1=周一、2=周二…5=周五)作为键,对应不同的起止小时
  • 遍历未来60天的每一天,判断当天所属星期几
  • 根据规则生成对应时段的日期对象,最终按星期几分组存储

代码实现

// 配置各工作日的时段:键对应Date.getDay()返回值(1=周一,2=周二…5=周五)
const weekdaySchedule = {
  1: { startHour: 9, endHour: 15 },   // 周一:9:00-15:00
  2: { startHour: 8, endHour: 16 },   // 周二:8:00-16:00
  3: { startHour: 8, endHour: 17 },   // 周三:8:00-17:00
  4: { startHour: 9, endHour: 16 },   // 周四:9:00-16:00
  5: { startHour: 8, endHour: 14 }    // 周五:8:00-14:00
};

function generateWeekdayTimeSlots() {
  // 初始化按星期几分组的结果容器
  const groupedSlots = {
    1: [], 2: [], 3: [], 4: [], 5: []
  };
  const today = new Date();

  for (let i = 0; i < 60; i++) {
    // 生成第i天的日期(每次创建新实例,避免修改原日期对象)
    const currentDay = new Date(today);
    currentDay.setDate(today.getDate() + i);

    const dayNum = currentDay.getDay();
    // 只处理配置过的工作日
    if (weekdaySchedule[dayNum]) {
      const { startHour, endHour } = weekdaySchedule[dayNum];
      
      // 生成时段的开始/结束时间
      const start = new Date(currentDay);
      start.setHours(startHour, 0, 0, 0);
      
      const end = new Date(currentDay);
      end.setHours(endHour, 0, 0, 0);

      // 存入对应星期几的集合
      groupedSlots[dayNum].push({
        date: currentDay.toLocaleDateString(),
        weekday: ['周日','周一','周二','周三','周四','周五','周六'][dayNum],
        startTime: start.toLocaleTimeString(),
        endTime: end.toLocaleTimeString()
      });
    }
  }

  return groupedSlots;
}

// 调用示例
const timeSlots = generateWeekdayTimeSlots();
console.log('周一所有时段:', timeSlots[1]);
console.log('周二所有时段:', timeSlots[2]);

关键细节说明

  • Date.getDay()返回0(周日)到6(周六),所以用1-5对应周一到周五
  • 每次循环创建新的Date实例,避免因setDate/setHours修改原对象导致的日期混乱
  • 可直接修改weekdaySchedule调整各星期的时段,也可扩展配置包含周末
  • 若需要扁平数组而非分组结构,只需把结果存入一个数组即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:20:52