使用moment.js获取指定日期间隔内每个月的首日与末日
调整要点
- 克隆原始起始日期用于遍历,避免修改原始传入的日期对象
- 调整循环判定条件,将结束日期所在的月份也纳入结果集
- 区分首月和后续月份的起始日期规则,首月用原始传入的开始日期,其余月份取当月首日
- 使用moment内置的
endOf('month')方法直接获取当月最后一天,无需手动拼接日期
完整可运行代码
var startDate = moment('2021-08-23'); var endDate = moment('2022-03-22'); var months = []; if (endDate.isBefore(startDate)) { throw "End date must be greater than start date." } // 克隆起始日期,避免修改原始值 let currentMonth = startDate.clone(); while (currentMonth.isBefore(endDate) || currentMonth.isSame(endDate, 'month')) { let currentStart; // 首月用原始开始日期,其他月份用当月第一天 if (currentMonth.isSame(startDate, 'month')) { currentStart = startDate.format('YYYY-MM-DD'); } else { currentStart = currentMonth.startOf('month').format('YYYY-MM-DD'); } // 取当月最后一天 let currentEnd = currentMonth.clone().endOf('month').format('YYYY-MM-DD'); months.push([currentStart, currentEnd]); // 跳转到下一个月 currentMonth.add(1, 'month'); } console.log(months);
输出说明
运行代码后输出的结果和你预期的基本一致,唯一差异为2022年并非闰年,2月实际最后一天为28号,代码会自动输出正确的2022-02-28,若有特殊需求可自行调整该部分逻辑。
内容的提问来源于stack exchange,提问作者Sebbie
相关产品推荐
相关产品推荐

