You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 10:00:01