ReactJS/JavaScript按周生成日期范围的异常问题排查
问题分析与解决方案
核心问题原因
- 时区偏移引发日期显示异常:使用
new Date('YYYY-MM-DD')会按本地时区解析为当日00:00,但toISOString()返回UTC时间,若本地时区在UTC以西,本地00:00对应前一天UTC时间,导致日期展示偏差。 - 周结束日计算逻辑错误:原
getSingleWeekRange中,lastDate.setDate(firstDate.getDate() + 6)依赖修改后的firstDate的日期数,跨月时会出现日期溢出(比如3月31日加6天,若lastDate初始为4月,setDate(37)会错误计算为5月7日)。 - 数组顺序颠倒:示例返回顺序异常,大概率是操作时误反转数组,修正后的代码会保持从早到晚的正确顺序。
修正后的代码
单周范围计算函数
const getSingleWeekRange = (startDate) => { // 基于UTC创建日期,彻底避免时区偏移影响 const firstDate = new Date(Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate())); const dayOfWeek = firstDate.getUTCDay(); // 0=周日,1=周一...6=周六 // 调整到当周第一天(周日) firstDate.setUTCDate(firstDate.getUTCDate() - dayOfWeek); // 直接从当周第一天加6天得到周结束日 const lastDate = new Date(firstDate); lastDate.setUTCDate(lastDate.getUTCDate() + 6); return `${firstDate.toISOString().slice(0, 10)} to ${lastDate.toISOString().slice(0, 10)}`; };
日期范围周数组生成函数
const getWeeksInRange = (startDate, endDate) => { const weeks = []; // 转换为UTC日期对象,统一计算基准 const startUtc = new Date(startDate); let currentDate = new Date(Date.UTC(startUtc.getFullYear(), startUtc.getMonth(), startUtc.getDate())); const endUtc = new Date(endDate); const futureDate = new Date(Date.UTC(endUtc.getFullYear(), endUtc.getMonth(), endUtc.getDate())); while (currentDate <= futureDate) { weeks.push(getSingleWeekRange(currentDate)); // 移动到下一周的第一天 currentDate.setUTCDate(currentDate.getUTCDate() + 7); } return weeks; };
测试结果
调用getWeeksInRange('2024-04-02', '2024-04-30'),返回正确顺序的周范围数组:
[ "2024-03-31 to 2024-04-06", "2024-04-07 to 2024-04-13", "2024-04-14 to 2024-04-20", "2024-04-21 to 2024-04-27", "2024-04-28 to 2024-05-04" ]
自定义周起始日
若需将周起始日设为周一,修改firstDate的调整逻辑即可:
// 调整到当周第一天(周一) firstDate.setUTCDate(firstDate.getUTCDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1));
内容的提问来源于stack exchange,提问作者Ethan
相关产品推荐
相关产品推荐

