使用要点
- 跑完文件,输出里会留下标记——
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());