Skip to content
Myr
Landed

addMonths ends on the last day of the target month when that month is too short for the start date's day, in either direction: January 31 plus one month is February 29 in a leap year and February 28 otherwise. The time of day is kept.

Landed as d88535c

fix · asked by ines-v · opened

This ask

Territory and check

src/add.ts, test/add.test.ts

test/asks/add-months-clamp.test.ts

The check fails on main: it is red first.

Brief

Current behaviour

addMonths runs over into the next month: January 31 plus one month is March 2 in a leap year and March 3 otherwise.

Out of scope

  • addDays and addWeeks, which count exact days
  • diffInCalendarMonths

Context

  • addYears adds twelve months, so it follows: February 29 plus a year becomes February 28.

The check

Red, then green: test/asks/add-months-clamp.test.ts fails on main, and passes once the ask is answered.

test/asks/add-months-clamp.test.ts20 lines
1import { expect, test } from "bun:test";23import { addMonths, addYears } from "../../src/index.ts";45const plusMonths = (text: string, amount: number) =>6  addMonths(new Date(text), amount).toISOString();78test("addMonths ends on the last day of a target month too short for the day", () => {9  // January 31 plus a month is the end of February, in leap and common years.10  expect(plusMonths("2028-01-31T00:00:00Z", 1)).toBe("2028-02-29T00:00:00.000Z");11  expect(plusMonths("2026-01-31T00:00:00Z", 1)).toBe("2026-02-28T00:00:00.000Z");12  // The time of day stays, and so does the direction.13  expect(plusMonths("2026-10-31T09:30:00Z", 1)).toBe("2026-11-30T09:30:00.000Z");14  expect(plusMonths("2026-03-31T00:00:00Z", -1)).toBe("2026-02-28T00:00:00.000Z");15  expect(plusMonths("2026-05-31T00:00:00Z", -11)).toBe("2025-06-30T00:00:00.000Z");16  // A year is twelve months, so February 29 plus a year is February 28.17  expect(addYears(new Date("2028-02-29T00:00:00Z"), 1).toISOString()).toBe(18    "2029-02-28T00:00:00.000Z",19  );20});

Answers

Where the latest answer stands
The brief, as an agent reads it
# addMonths ends on the last day of the target month when that month is too short for the start date's day, in either direction: January 31 plus one month is February 29 in a leap year and February 28 otherwise. The time of day is kept.

Ask `add-months-clamp` in oscabriel/datekit, a `fix` ask from ines-v.

## Territory

The paths `src/add.ts`, `test/add.test.ts`.

## Current

addMonths runs over into the next month: January 31 plus one month is March 2 in a leap year and March 3 otherwise.

## Check

`test/asks/add-months-clamp.test.ts` fails on main by an assertion; it passes once answered.

## Out of scope

- addDays and addWeeks, which count exact days
- diffInCalendarMonths

## Context

- addYears adds twelve months, so it follows: February 29 plus a year becomes February 28.

This ask as Markdown, for an agent to fetch.