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

Moment.js startOf正常但endOf返回无效值问题求助

Moment.js 获取指定月份起止日期时月末计算错误的修复

问题出在你两次调用了today.add(factor, 'M')——Moment.js的add方法会直接修改原日期对象,第一次调用后today已经偏移到目标月份,第二次再叠加同一个factor,相当于把日期又多偏移了一次,自然月末就错了。

修复后的代码如下:

// 获取指定月份起止日期的函数
function Calculate() {
  // 获取输入的月份
  const month = document.getElementById('month').value;
  console.log('You entered', month);

  // 获取当前日期
  const today = moment();

  // 计算当前月份与目标月份的差值
  const factor = month - (today.month() + 1);

  // 仅做一次月份偏移,得到目标月份的日期对象
  const targetMonth = today.clone().add(factor, 'M');

  // 基于目标月份分别计算月初和月末
  const startOfMonth = targetMonth.clone().startOf('month').format('DD-MM-YYYY');
  const endOfMonth = targetMonth.clone().endOf('month').format('DD-MM-YYYY');

  console.log('Ranges', startOfMonth, endOfMonth);
};

对应的HTML部分可以保持不变:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

<label>输入月份以获取起止日期</label><br />
<input type="number" id="month"><br /><br />
<input type="button" value="计算" onClick="Calculate()">

核心改动点:

  • 只对原日期对象做一次月份偏移,得到targetMonth
  • 后续计算月初、月末时,都基于targetMonth克隆新对象操作,避免修改原对象导致的二次偏移
  • 用startOf('month')替代startOf('M'),可读性更强(两者功能完全一致)

内容的提问来源于stack exchange,提问作者Zain Ul Abidin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 23:24:31