setDate And setMonth Roll Past Month Ends

setDate and setMonth carry overflow into the following month — January 31 plus one month lands on March 3 — while day 0 steps back to the previous month-end.

JavascriptData Integrity

Code

javascriptsnippet
19 lines
// 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());

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Working with it

Lines come out tagged jan 31 + 1 day:, jan 31 + 1 month:, clamped:, so you can tell which operation printed each one.

Output is labeled for readability — expect lines prefixed with jan 31 + 1 day:, jan 31 + 1 month:, clamped:.

Statements that matter

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);

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit.