如何在JavaScript中查找指定时间段内目标星期的首尾日期?
JavaScript:查找时间范围内目标星期的首个和末次日期
需求描述
给定DD/MM/YYYY格式的时间范围字符串,以及一组目标星期缩写(如['MON', 'FRI']),实现函数找出该时间段内第一个属于目标星期的日期,以及最后一个属于目标星期的日期。
示例说明
示例1
- 时间范围:2023年1月28日至2023年2月21日
- 目标星期:
['MON', 'FRI'] - 预期结果:返回
2023年1月30日(周一)和2023年2月20日(周一)
示例2
- 时间范围:2023年1月28日至2023年2月25日
- 目标星期:
['MON', 'FRI'] - 预期结果:返回
2023年1月30日(周一)和2023年2月24日(周五)
示例3
- 时间范围:2023年1月31日至2023年2月25日
- 目标星期:
['MON', 'FRI'] - 预期结果:返回
2023年2月3日(周五)和2023年2月24日(周五)
完善后的代码实现
// 星期缩写与Date.getDay()返回值的映射(0=周日, 1=周一...6=周六) const dayMap = { SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6 }; // 将Date对象格式化为中文日期字符串 const formatDate = (date) => { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const weekNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; return `${year}年${month}月${day}日(${weekNames[date.getDay()]})`; }; const findDate = (startDateStr, endDateStr, targetDays) => { // 解析DD/MM/YYYY格式的字符串为Date对象 const parseDate = (dateStr) => { const [day, month, year] = dateStr.split('/').map(Number); return new Date(year, month - 1, day); }; const startDate = parseDate(startDateStr); const endDate = parseDate(endDateStr); // 把目标星期转为对应的数值集合 const targetDayValues = targetDays.map(day => dayMap[day.toUpperCase()]); // 查找第一个符合条件的日期 let firstMatch = null; let currentDate = new Date(startDate); while (currentDate <= endDate) { if (targetDayValues.includes(currentDate.getDay())) { firstMatch = new Date(currentDate); break; } currentDate.setDate(currentDate.getDate() + 1); } // 查找最后一个符合条件的日期 let lastMatch = null; currentDate = new Date(endDate); while (currentDate >= startDate) { if (targetDayValues.includes(currentDate.getDay())) { lastMatch = new Date(currentDate); break; } currentDate.setDate(currentDate.getDate() - 1); } // 返回格式化结果,无匹配时提示 return { first: firstMatch ? formatDate(firstMatch) : '无符合条件的日期', last: lastMatch ? formatDate(lastMatch) : '无符合条件的日期' }; }; // 测试示例1 const startDate1 = "28/01/2023"; const endDate1 = "21/02/2023"; const days1 = ['MON', "FRI"]; console.log(findDate(startDate1, endDate1, days1)); // 输出:{ first: '2023年01月30日(周一)', last: '2023年02月20日(周一)' } // 测试示例2 const startDate2 = "28/01/2023"; const endDate2 = "25/02/2023"; console.log(findDate(startDate2, endDate2, days1)); // 输出:{ first: '2023年01月30日(周一)', last: '2023年02月24日(周五)' } // 测试示例3 const startDate3 = "31/01/2023"; const endDate3 = "25/02/2023"; console.log(findDate(startDate3, endDate3, days1)); // 输出:{ first: '2023年02月03日(周五)', last: '2023年02月24日(周五)' }
代码关键说明
日期处理:
parseDate函数解决DD/MM/YYYY格式到Date对象的转换,注意月份需减1(Date对象的月份为0起始)。formatDate负责将Date对象转为用户易读的中文日期格式,包含星期名称。
匹配逻辑:
- 首个匹配:从起始日期开始逐日递增检查,找到第一个符合目标星期的日期即停止。
- 末次匹配:从结束日期开始逐日递减检查,找到最后一个符合目标星期的日期即停止。
边界兼容:
- 如果时间范围内没有符合条件的日期,返回明确的提示文本。
内容的提问来源于stack exchange,提问作者Karim SOUARI
相关产品推荐
相关产品推荐

