← 中文资源

简体中文版本

setDate 与 setMonth 跨过月末进位

setDate/setMonth 遇到溢出天数会向前进位:1 月 31 日设成 2 月会落进 3 月 3 日,想停在月末必须先钳住目标月天数;setDate(0) 则回退到上个月最后一天。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

jan 31 + 1 day: Sun Feb 01 2026
jan 31 + 1 month: Tue Mar 03 2026
clamped: Sat Feb 28 2026
mar 15 -> day 0: Sat Feb 28 2026

使用要点

  • 跑完文件,输出里会留下标记——jan 31 + 1 day:、jan 31 + 1 month:、clamped:。

常见问题

依赖情况复杂吗?

一点也不复杂:零依赖,没有要锁版本或审计的东西。

核心语句

d.setDate(32);                   // January has 31 days -> rolls forward into February 1
console.log('jan 31 + 1 day:', d.toDateString());
const g = new Date(2026, 2, 15); // 2026-03-15
g.setDate(0);
const e = new Date(2026, 0, 31);

代码示例

// setDate rolls over when the value exceeds the current month's day count
const d = new Date(2026, 0, 31); // 2026-01-31 (local time zone, months are zero-based)
d.setDate(32);                   // January has 31 days -> rolls forward into February 1
console.log('jan 31 + 1 day:', d.toDateString());

// setMonth works the same: January 31 set to February -> February 31 does not exist, so it overflows into March 3
const e = new Date(2026, 0, 31);
e.setMonth(1);
console.log('jan 31 + 1 month:', e.toDateString());

// to land on month end: clamp to the target month's last day before calling setMonth
const f = new Date(2026, 0, 31);
f.setMonth(1, 28);
console.log('clamped:', f.toDateString());

// setDate(0) backs up to the last day of the previous month
const g = new Date(2026, 2, 15); // 2026-03-15
g.setDate(0);
console.log('mar 15 -> day 0:', g.toDateString());