Generate monthly recurring dates in JavaScript
Advanced · 4 min read
Subscriptions, rent, loan repayments and monthly reports all repeat "on the same day every month". That sounds simple until someone signs up on the 31st. February has no 31st, so you have to pick a nearby day. What happens in March is where many billing systems go wrong.
In this tutorial you will write two schedules starting from 31 January 2026. monthlyAnchored always aims for the original day, the 31st. monthlyChained works from each previous result. They agree in February and disagree from March onwards, and one of them slowly moves every payment to the 28th. You need to know how to make a date from parts, that months count from 0, and how loops and arrays work.
Month rollover
When you give new Date a day that is too big for the month, it doesn't fail. It rolls the extra days into the next month:
const d = new Date(2026, 1, 31); // "31 February 2026"
console.log(d.getMonth(), d.getDate()); // 2 3
February 2026 has 28 days, so 31 February becomes 3 March. For a monthly bill, that skips February entirely. So we need to clamp the day: use the smaller of the day we want and the number of days in the month.
Anchored and chained
- Anchored: every date is worked out from the start date. "The 31st, or the last day if the month is shorter."
- Chained: every date is worked out from the one before it. "One month after the last payment."
Here is the exercise. Try it on your own first if you like, then read on and we will build it step by step.
54 A monthly schedule that does not drift
hardGenerate the next four monthly dates from 31 January 2026. Do it twice: anchored to the original day of the month, and chained from each previous result. The two disagree, and one of them is a billing bug.
Stuck? Three hints, smallest first
- 1. Anchored means every date is computed from the ORIGINAL day number, clamped to the month it lands in.
- 2. Chained means each date is one month after the last result, so a clamp is permanent.
- 3. Start from the 31st, where February forces the clamp.
Step 1: helpers
const iso = (d) => d.getFullYear() + '-' +
String(d.getMonth() + 1).padStart(2, '0') + '-' +
String(d.getDate()).padStart(2, '0');
const daysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();
console.log(daysInMonth(2026, 1)); // 28
console.log(daysInMonth(2026, 3)); // 30
iso shows a date as YYYY-MM-DD. daysInMonth uses day 0 of the next month, which is the last day of this one. February 2026 has 28 days and April has 30.
Step 2: the wrong turn, setMonth
const naive = new Date(2026, 0, 31);
naive.setMonth(naive.getMonth() + 1);
console.log(iso(naive)); // '2026-03-03'
Adding a month to 31 January with setMonth asks for 31 February, which rolls over to 3 March. The February payment has vanished.
Step 3: clamp the day
const clampDay = (year, month, wanted) =>
new Date(year, month, Math.min(wanted, daysInMonth(year, month)));
console.log(iso(clampDay(2026, 1, 31))); // '2026-02-28'
console.log(iso(clampDay(2026, 2, 31))); // '2026-03-31'
Math.min picks the smaller number. In February the month is shorter, so we get the 28th. In March the 31st exists, so we get it.
Step 4: the chained schedule
The chained version takes the previous result, moves to the 1st of the next month, then clamps the previous result's day:
function monthlyChained(start, count) {
const out = [new Date(start)];
while (out.length < count) {
const previous = out[out.length - 1];
const day = previous.getDate();
const next = new Date(previous.getFullYear(), previous.getMonth() + 1, 1);
next.setDate(Math.min(day, daysInMonth(next.getFullYear(), next.getMonth())));
out.push(next);
}
return out;
}
const endOfJanuary = new Date(2026, 0, 31);
console.log(monthlyChained(endOfJanuary, 4).map(iso).join(' ')); // 2026-01-31 2026-02-28 2026-03-28 2026-04-28
Starting at the 1st of the next month avoids the rollover. But look at March: after February became the 28th, the next step only remembers "28", so March is the 28th too, and so is every month after. The customer who signed up on the 31st is now billed on the 28th forever.
Step 5: the anchored schedule
The anchored version remembers the original day and works each month out from the start date:
function monthlyAnchored(start, count) {
const anchorDay = start.getDate();
const out = [];
for (let i = 0; i < count; i++) {
const first = new Date(start.getFullYear(), start.getMonth() + i, 1);
const year = first.getFullYear();
const month = first.getMonth();
out.push(new Date(year, month, Math.min(anchorDay, daysInMonth(year, month))));
}
return out;
}
console.log(monthlyAnchored(endOfJanuary, 4).map(iso).join(' ')); // 2026-01-31 2026-02-28 2026-03-31 2026-04-30
February is still clamped to the 28th, but March goes back to the 31st and April uses its last day, the 30th.
new Date(start.getFullYear(), start.getMonth() + i, 1) is the 1st of the month i months after the start. If the month number goes past 11, JavaScript rolls it into the next year, so we read the real year and month back from first.
Step 6: years and long schedules
console.log(monthlyAnchored(new Date(2025, 11, 31), 3).map(iso).join(' ')); // 2025-12-31 2026-01-31 2026-02-28
console.log(iso(monthlyAnchored(endOfJanuary, 13)[12])); // '2027-01-31'
console.log(monthlyAnchored(new Date(2026, 0, 15), 4).map(iso).join(' ')); // 2026-01-15 2026-02-15 2026-03-15 2026-04-15
The schedule crosses the year end without help, and a year later it is still on the 31st. For a day every month has, like the 15th, both schedules give the same dates.
There is a bonus to anchoring: because each date comes from the start date, you can work out the 13th payment without building the first 12.
The full solution
The panel has both schedules. It prints them side by side from 31 January 2026. The checks cover the permanent clamp in the chained version, the last-day rule, a day every month has, the year end and a count of one. Press Run to see them.
const iso = (d) => d.getFullYear() + '-' +
String(d.getMonth() + 1).padStart(2, '0') + '-' +
String(d.getDate()).padStart(2, '0');
const daysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();
// Anchored: the original day number is re-applied to each month, so a short
// February borrows nothing from March.
function monthlyAnchored(start, count) {
const anchorDay = start.getDate();
const out = [];
for (let i = 0; i < count; i++) {
const first = new Date(start.getFullYear(), start.getMonth() + i, 1); // handles the year roll
const year = first.getFullYear();
const month = first.getMonth();
out.push(new Date(year, month, Math.min(anchorDay, daysInMonth(year, month))));
}
return out;
}
// Chained: each step works from the previous RESULT, so the February clamp sticks.
function monthlyChained(start, count) {
const out = [new Date(start)];
while (out.length < count) {
const previous = out[out.length - 1];
const day = previous.getDate();
const next = new Date(previous.getFullYear(), previous.getMonth() + 1, 1);
next.setDate(Math.min(day, daysInMonth(next.getFullYear(), next.getMonth())));
out.push(next);
}
return out;
}
const endOfJanuary = new Date(2026, 0, 31);
console.log('anchored:', monthlyAnchored(endOfJanuary, 4).map(iso).join(' '));
console.log('chained :', monthlyChained(endOfJanuary, 4).map(iso).join(' '), '<- stuck on the 28th');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('anchored to the 31st, February clamps and March recovers', monthlyAnchored(endOfJanuary, 4).map(iso), ['2026-01-31', '2026-02-28', '2026-03-31', '2026-04-30']);
test('chained, the clamp is permanent', monthlyChained(endOfJanuary, 4).map(iso), ['2026-01-31', '2026-02-28', '2026-03-28', '2026-04-28']);
test('every anchored date is the last day of its month', monthlyAnchored(endOfJanuary, 4).every((d) => d.getDate() === daysInMonth(d.getFullYear(), d.getMonth())), true);
test('which is not true of the chained ones', monthlyChained(endOfJanuary, 4).every((d) => d.getDate() === daysInMonth(d.getFullYear(), d.getMonth())), false);
test('for a day every month has, the two agree', same(monthlyAnchored(new Date(2026, 0, 15), 4).map(iso), monthlyChained(new Date(2026, 0, 15), 4).map(iso)), true);
test('and that schedule is unremarkable', monthlyAnchored(new Date(2026, 0, 15), 4).map(iso), ['2026-01-15', '2026-02-15', '2026-03-15', '2026-04-15']);
test('a schedule crossing the year end', monthlyAnchored(new Date(2025, 11, 31), 3).map(iso), ['2025-12-31', '2026-01-31', '2026-02-28']);
test('thirteen months on, the anchor is still the 31st', iso(monthlyAnchored(endOfJanuary, 13)[12]), '2027-01-31');
test('a count of one is just the start date', monthlyAnchored(endOfJanuary, 1).map(iso), ['2026-01-31']);
Both functions clamp February to the 28th, and after that they part company. The anchored one remembers that the customer signed up on the 31st and bills on the 31st again in March; the chained one has forgotten, and bills on the 28th for the rest of time. Four steps is enough to see it; twelve is enough for a customer to notice.
The rule generalises past dates: when you generate a sequence by repeatedly applying a lossy operation to its own output, the loss compounds. Keep the original input and derive each element from it. That also makes the nth element computable without generating the first n-1, which is worth having when the schedule is long.
Common mistakes
- Using
setMonth(getMonth() + 1)on the 29th, 30th or 31st. The day can roll into the following month. - Building each date from the one before. Once a short month clamps the day, the clamp sticks. Keep the original day and work from it.
- Testing only with the 15th. Every month has a 15th, so both versions look fine. Test with the 31st.
Try it yourself
- Use
monthlyAnchoredto list a year of rent dates starting on 30 January 2026. - Write
nthMonthly(start, n)that returns only the nth date, without building the whole list. - Make a yearly schedule starting on 29 February 2024. What should 2025 show?