React中如何基于Moment.js以对象形式获取周数据
使用Moment.js获取指定月份的周数据
核心实现代码
function getMonthWeeks(year, month) { // Moment.js月份为0-based(0=1月,11=12月) const monthStart = moment([year, month]).startOf('month'); const monthEnd = moment([year, month]).endOf('month'); const monthWeeks = []; // 定位到当月第一周的起始日(默认周日为一周开始,需周一开头则用startOf('isoWeek')) let currentWeekStart = monthStart.clone().startOf('week'); while (currentWeekStart.isBefore(monthEnd) || currentWeekStart.isSame(monthEnd, 'day')) { const weekDays = {}; // 遍历一周7天,生成键为0-6的moment对象集合 for (let i = 0; i < 7; i++) { weekDays[i] = currentWeekStart.clone().add(i, 'days'); } monthWeeks.push(weekDays); currentWeekStart.add(1, 'week'); } return monthWeeks; } // 调用示例:获取2024年1月的周数据 const targetWeeks = getMonthWeeks(2024, 0); console.log(targetWeeks);
关键说明
- 函数接收
year(四位数字年份)和month(0-11的月份值)作为参数,返回的数组中每个元素是一个对象,键0对应周日、1对应周一……6对应周六,值为对应日期的moment对象。 - 若需以周一作为一周起始,只需将代码中
startOf('week')替换为startOf('isoWeek'),此时键0对应周一,6对应周日。 - 如果需要仅保留周中属于当前月份的日期,可在赋值时添加判断:
const day = currentWeekStart.clone().add(i, 'days'); if (day.month() === month) { weekDays[i] = day; }
内容的提问来源于stack exchange,提问作者Laxman Nemane
相关产品推荐
相关产品推荐

