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

momentjs startOf('month')失效:获取月份首尾日期输出异常

Why isn't moment.js's startOf('month') working as expected?

Ah, I see the issue here—this is a super common gotcha with Moment.js because of how its core objects behave!

The root problem is that Moment.js objects are mutable. Methods like startOf() and endOf() don’t return a brand-new modified Moment instance—they directly alter the original object you call them on. Let’s break down exactly what’s happening in your code:

  1. let month = moment().month(2) creates a Moment object pointing to March (remember, months are 0-indexed!) of the current year.
  2. When you call month.startOf('month'), this modifies the month variable in-place to now point to the first day of March.
  3. Next, month.endOf('month') modifies that same month variable again, shifting it to the last moment of March.
  4. By the time you run console.log, all three references (month, month.startOf('month'), month.endOf('month')) point to the same modified object—the final one you updated, which is the end of the month.

The Fix: Clone Your Moment Objects

To keep your original date intact and get distinct values for start/end of the month, you need to create copies using the clone() method before calling startOf() or endOf(). Here’s how to adjust your code:

let month = moment().month(2);
console.log(month.clone(), month.clone().startOf('month'), month.clone().endOf('month'));

For even better readability, you can assign each value to separate variables:

const originalMonth = moment().month(2);
const startOfMonth = originalMonth.clone().startOf('month');
const endOfMonth = originalMonth.clone().endOf('month');

console.log(originalMonth, startOfMonth, endOfMonth);

Now each operation works on a separate clone of the original Moment object, so you’ll get the original date, the start of the month, and the end of the month as three distinct, correct values.

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:25:24