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.
Code
// 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 2026Working 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
Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Unix Timestamp ConverterConvert between Unix timestamps and human-readable dates in both directions. Supports seconds and milliseconds, with UTC and local timezone display options.
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit.
Report a problem with this exampleOpens a pre-filled issue on GitHub.