如何使用moment.js获取指定月份每一周的开始与结束日期
实现代码
// 入参说明:year为目标年份,month为目标自然月(取值1-12) function getMonthWeekRanges(year, month) { // 定位到目标月份第一天 const targetMonthStart = moment([year, month - 1]) // 定位到目标月份最后一天 const targetMonthEnd = targetMonthStart.clone().endOf('month') const weekRanges = [] // 从当月第一天所在周的起始开始遍历 let currentWeekStart = targetMonthStart.clone().startOf('week') while (currentWeekStart.isBefore(targetMonthEnd)) { const currentWeekEnd = currentWeekStart.clone().endOf('week') // 限制周起始不早于当月第一天 const realStart = currentWeekStart.isBefore(targetMonthStart) ? targetMonthStart.clone() : currentWeekStart // 限制周结束不晚于当月最后一天 const realEnd = currentWeekEnd.isAfter(targetMonthEnd) ? targetMonthEnd.clone() : currentWeekEnd weekRanges.push({ startDate: realStart.toDate(), endDate: realEnd.toDate(), formatText: `${realStart.format('D MMM YYYY')} - ${realEnd.format('D MMM YYYY')}` }) // 跳转至下一周 currentWeekStart.add(1, 'week') } return weekRanges } // 调用示例:获取2021年8月的所有周范围 const augWeekList = getMonthWeekRanges(2021, 8) console.log('In August month') console.log('In Array of object') augWeekList.forEach((item, idx) => { console.log(`${idx + 1}. ${item.formatText}`) })
补充说明
- 上述代码默认周起始为周日,和你给出的示例输出完全匹配。如果需要适配国内周起始为周一的习惯,可在代码初始化阶段全局配置moment:
moment.locale('zh-cn', { week: { dow: 1 // 1代表周一为周起始,0为周日 } })
- 函数返回的数组长度即为对应月份的周数,数组每一项包含原始日期对象和格式化后的范围文本,可按需取用。
内容的提问来源于stack exchange,提问作者toyyy
相关产品推荐
相关产品推荐

