Add Months With End-Of-Month Clamping

Add or subtract months in UTC while clamping the day to the target month's last day, avoiding date rollover bugs.

TypescriptData Integrity

Code

typescriptsnippet
31 lines
export function daysInMonth(year: number, monthIndex: number): number {
  if (!Number.isInteger(year) || !Number.isInteger(monthIndex)) {
    throw new TypeError("year and monthIndex must be integers");
  }
  return new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate();
}

// Add months with end-of-month clamping.
export function addMonthsClamped(date: Date, months: number): Date {
  if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
    throw new RangeError("date must be a valid Date");
  }
  if (!Number.isInteger(months)) throw new TypeError("months must be an integer");
  const target = new Date(Date.UTC(
    date.getUTCFullYear(),
    date.getUTCMonth() + months,
    1,
    date.getUTCHours(),
    date.getUTCMinutes(),
    date.getUTCSeconds(),
    date.getUTCMilliseconds(),
  ));
  const day = Math.min(date.getUTCDate(), daysInMonth(target.getUTCFullYear(), target.getUTCMonth()));
  target.setUTCDate(day);
  return target;
}

export function addYearsClamped(date: Date, years: number): Date {
  if (!Number.isInteger(years)) throw new TypeError("years must be an integer");
  return addMonthsClamped(date, years * 12);
}

How the snippet works

Count the functions daysInMonth, addMonthsClamped and addYearsClamped as the entire surface area of Add Months With End-Of-Month Clamping.

Invalid states are rejected up front: it throws TypeError and RangeError instead of continuing with bad data.

The return value is newly constructed — inputs are never handed back.

Applying it

The primary signature is export function daysInMonth(year: number, monthIndex: number)

daysInMonth is the public entry point; everything else in the file exists to support it.

Statements that matter

if (!Number.isInteger(months)) throw new TypeError("months must be an integer");
if (!Number.isInteger(years)) throw new TypeError("years must be an integer");
return new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate();

Interactive Tools for This Topic

FAQ

Does `daysInMonth` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Does the code validate its input?
The code refuses to continue: `TypeError` and `RangeError` is thrown while the state is still recoverable.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `daysInMonth`, `addMonthsClamped`, `addYearsClamped` at load time.