使用MomentJS在JavaScript中生成按月份分组的日期范围嵌套数组
用MomentJS实现按月份分组的日期嵌套数组
核心思路
利用MomentJS的日期格式化和比较能力,遍历指定日期范围时,按年份-月份的唯一标识对日期进行分组,最后转换为「月份名称 + 对应日期数组」的嵌套结构,避免跨年时同月份混淆。
解决方案代码
方法一:通过中间对象分组(更直观)
// 确保已引入MomentJS(浏览器可通过CDN,Node环境需npm安装) const moment = require('moment'); // 定义起止日期 const startDate = moment('2024-05-01'); const endDate = moment('2024-06-03'); // 存储月份分组的临时对象 const monthGroups = {}; let currentMoment = startDate.clone(); // 克隆起始日期,避免修改原对象 while (currentMoment.isSameOrBefore(endDate)) { // 生成唯一月份标识(防止跨年同月份冲突) const monthKey = currentMoment.format('YYYY-MM'); // 获取月份名称(如"May") const monthName = currentMoment.format('MMMM'); // 初始化当前月份的分组 if (!monthGroups[monthKey]) { monthGroups[monthKey] = { name: monthName, dates: [] }; } // 将当前日期转为原生Date对象,加入分组 monthGroups[monthKey].dates.push(currentMoment.toDate()); // 日期加1天 currentMoment.add(1, 'day'); } // 转换为期望的嵌套数组结构 const groupedDates = Object.values(monthGroups).map(group => [group.name, group.dates]); console.log(groupedDates);
方法二:遍历过程中直接分组(更高效)
const moment = require('moment'); const startDate = moment('2024-05-01'); const endDate = moment('2024-06-03'); const groupedDates = []; let currentMoment = startDate.clone(); let currentMonthGroup = null; while (currentMoment.isSameOrBefore(endDate)) { const currentMonthKey = currentMoment.format('YYYY-MM'); const currentMonthName = currentMoment.format('MMMM'); // 当月份变化时,新建分组并加入结果数组 if (!currentMonthGroup || currentMonthGroup.key !== currentMonthKey) { currentMonthGroup = { key: currentMonthKey, name: currentMonthName, dates: [] }; groupedDates.push([currentMonthGroup.name, currentMonthGroup.dates]); } currentMonthGroup.dates.push(currentMoment.toDate()); currentMoment.add(1, 'day'); } console.log(groupedDates);
输出结构说明
最终输出的groupedDates结构与你期望的一致:
[ ["May", [ new Date("2024-05-01T00:00:00"), new Date("2024-05-02T00:00:00"), // ... 5月所有日期 ]], ["June", [ new Date("2024-06-01T00:00:00"), new Date("2024-06-02T00:00:00"), new Date("2024-06-03T00:00:00") ]] ]
内容的提问来源于stack exchange,提问作者roblawford
相关产品推荐
相关产品推荐

