如何使用JavaScript获取上周周一至周日的日期区间
JavaScript 获取上周周一至周日的日期区间
以下是直接可用的代码实现,包含日期计算和格式化逻辑:
// 辅助函数:将日期格式化为 YYYY-MM-DD function formatDate(date) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } // 获取上周周一至周日的日期区间 function getLastWeekRange() { const today = new Date(); // 先获取上周的同一天(当前日期减7天) const lastWeekSameDay = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000); const dayOfWeek = lastWeekSameDay.getDay(); // 0=周日,1=周一...6=周六 // 计算上周周一:调整上周同一天到周一 const lastWeekMonday = new Date(lastWeekSameDay); const diffToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1; lastWeekMonday.setDate(lastWeekMonday.getDate() - diffToMonday); // 计算上周周日:周一加6天 const lastWeekSunday = new Date(lastWeekMonday); lastWeekSunday.setDate(lastWeekSunday.getDate() + 6); return { start: formatDate(lastWeekMonday), end: formatDate(lastWeekSunday) }; } // 调用示例 const lastWeek = getLastWeekRange(); console.log(`上周区间:${lastWeek.start} 至 ${lastWeek.end}`);
逻辑说明
- 先通过当前日期减去7天,得到上周的同一天作为基准点
- 根据基准点的星期数调整到上周周一:如果基准点是周日(
getDay()=0),需要往前推6天;其他星期数则往前推(星期数-1)天 - 上周周日直接由周一加6天得到
- 辅助函数
formatDate负责将日期对象转为标准的YYYY-MM-DD格式,方便后续使用
内容的提问来源于stack exchange,提问作者iarchangel
相关产品推荐
相关产品推荐

