Emmanuel Akinfulubi

JavaScriptBasic

Days in a month without a lookup table in JavaScript

Intermediate · 4 min read

How many days does February have this year? Calendars, booking forms, rent calculators and "last day of the month" reminders all need that answer. The usual approach is a table of twelve numbers plus a leap-year rule. JavaScript's Date can do it in one line, with no table at all.

In this tutorial you will write daysInMonth(year, month) using a small trick of the Date constructor. Then you'll see the same trick cause a quiet bug, asking for 31 February and getting March, and write safeDate to stop it. You need to know what a function is and how to create a date with new Date(year, month, day).

Two things to know about new Date

First, months count from 0. January is 0, February is 1, December is 11. Days count from 1 as usual.

JavaScript

const d = new Date(2026, 1, 14);
console.log(d.getMonth()); // 1, which means February
console.log(d.getDate());  // 14

Second, the day is not checked. JavaScript treats it as "this many days from the start of the month", so a day that's too big or too small just keeps counting into the next or previous month. That sounds odd, and it is exactly what makes this exercise work.

A helper to see dates clearly

Printing a whole Date shows a long string with a time zone. To keep things readable we'll use a small iso helper that prints yyyy-mm-dd:

JavaScript

const iso = (d) =>
  d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
console.log(iso(new Date(2026, 0, 5))); // 2026-01-05

The + 1 turns the 0-based month back into the number people use.

Here is the exercise. Try it on your own first if you like, or read on and we will build it together.

126 How many days that month has

fair

Work out the number of days in any month of any year without a lookup table and without your own leap-year rule. Then show what happens when you ask for a day the month does not have, such as the 31st of February, and clamp it instead.

Stuck? Three hints, smallest first
  1. 1. Day 0 of a month is the last day of the month before it.
  2. 2. So new Date(year, month + 1, 0) lands on the last day of month.
  3. 3. A day number out of range does not throw. It counts forward from the first of the month.

Step 1: day 0 is the day before the 1st

If day 1 is the first of the month, day 0 is one day earlier: the last day of the month before.

Step 1

const iso = (d) =>
  d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
console.log(iso(new Date(2026, 2, 0))); // 2026-02-28: day 0 of March
console.log(iso(new Date(2026, 0, 0))); // 2025-12-31: day 0 of January
console.log(iso(new Date(2026, 0, -1))); // 2025-12-30

Day 0 of January even steps back into the previous year, and a negative day keeps counting backwards.

Step 2: daysInMonth

So to find the length of a month, ask for day 0 of the next month and read its day number:

Step 2

function daysInMonth(year, month) {
  return new Date(year, month + 1, 0).getDate();
}
console.log(daysInMonth(2026, 1)); // 28: February 2026
console.log(daysInMonth(2028, 1)); // 29: 2028 is a leap year
console.log(daysInMonth(2026, 11)); // 31: December, using month 12 for the next month
const lengths2026 = Array.from({ length: 12 }, (_, m) => daysInMonth(2026, m));
console.log(lengths2026.join(' ')); // 31 28 31 30 31 30 31 31 30 31 30 31

For December, month + 1 is 12, which isn't a real month. Date rolls it into January of the next year, and day 0 of that is 31 December. No special case needed.

The leap-year rule comes for free too, including the tricky part about century years:

JavaScript

const daysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();
console.log(2100 % 4);            // 0: divisible by 4...
console.log(daysInMonth(2100, 1)); // 28: ...but 2100 is not a leap year

A hand-written "divisible by 4" check would get 2100 wrong. The engine already knows the whole rule.

Step 3: the same trick as a trap

Because days roll over, asking for a date that doesn't exist does not cause an error:

Step 3

const iso = (d) =>
  d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
const rolled = new Date(2026, 1, 31);
console.log(iso(rolled)); // 2026-03-03

February 2026 has 28 days, so the extra three keep counting into March. Imagine a monthly bill due "on the 31st": in February it quietly moves to 3 March, and nobody notices until a customer complains.

Step 4: clamp the day

When you want "the 31st, or the last day if the month is shorter", cap the day with Math.min:

Step 4

function daysInMonth(year, month) {
  return new Date(year, month + 1, 0).getDate();
}
function safeDate(year, month, day) {
  return new Date(year, month, Math.min(day, daysInMonth(year, month)));
}
const iso = (d) =>
  d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
console.log(iso(safeDate(2026, 1, 31))); // 2026-02-28
console.log(iso(safeDate(2026, 0, 31))); // 2026-01-31

Math.min picks the smaller number, so the day can never go past the end of the month. Clamping is one choice. The other is to reject the date and ask again. Either is fine, as long as you choose instead of letting the constructor choose.

The full solution

The answer panel has daysInMonth, safeDate and the iso helper. It prints all twelve month lengths for 2026, the rolled-over 31 February, and the clamped version. The checks also add up the months of 2026 and 2028 to 365 and 366. Press Run to see the output.

The answer

// Day 0 of the next month is the last day of this one, and the engine already
// knows every leap-year rule, so this needs no table and no arithmetic.
function daysInMonth(year, month) {
  return new Date(year, month + 1, 0).getDate();
}

// Out-of-range day numbers are not an error: they walk forward. Clamping keeps
// the answer inside the month the caller named.
function safeDate(year, month, day) {
  return new Date(year, month, Math.min(day, daysInMonth(year, month)));
}

const iso = (d) =>
  d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');

const lengths2026 = Array.from({ length: 12 }, (_, m) => daysInMonth(2026, m));
const rolled = new Date(2026, 1, 31);          // there is no 31 February
console.log('2026 month lengths:', lengths2026.join(' '));
console.log('asked for 31 February 2026, got', iso(rolled));
console.log('clamped instead:', iso(safeDate(2026, 1, 31)));

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.

9 checks

test('February 2026 has 28 days', daysInMonth(2026, 1), 28);
test('February 2028 has 29, without a leap rule of your own', daysInMonth(2028, 1), 29);
test('and 2100 is not a leap year, which the naive divide-by-four gets wrong', [daysInMonth(2100, 1), 2100 % 4], [28, 0]);
test('the twelve lengths of 2026', lengths2026, [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]);
test('which add up to a year, and 2028 to one day more', [lengths2026.reduce((a, b) => a + b, 0), Array.from({ length: 12 }, (_, m) => daysInMonth(2028, m)).reduce((a, b) => a + b, 0)], [365, 366]);
test('asking for 31 February silently gives 3 March', iso(rolled), '2026-03-03');
test('clamping keeps it in the month that was named', iso(safeDate(2026, 1, 31)), '2026-02-28');
test('day 0 of January is 31 December of the year before', [iso(new Date(2026, 0, 0)), new Date(2026, 0, 0).getMonth()], ['2025-12-31', 11]);
test('and a negative day keeps counting backwards', iso(new Date(2026, 0, -1)), '2025-12-30');

The whole exercise rests on one property of the Date constructor: the day argument is an offset from the first of the month, not a validated day number. Day 0 is therefore the day before the first, which is the last day of the previous month — that is why new Date(year, month + 1, 0) is the idiomatic length-of-month. It also means the engine's leap-year handling is doing the work, including the century rule that catches out hand-written versions: 2100 is divisible by 4 but is not a leap year.

The same permissiveness is the trap. new Date(2026, 1, 31) does not throw and does not return an invalid date; it quietly returns 3 March, because February 2026 runs out after 28 and the extra three days keep counting. A subscription renewal or a due date built that way slips into the next month and nobody notices until a customer is charged early. Decide which you want — clamp with Math.min, or reject the input — but do not let the constructor decide for you.

Common mistakes

  • Forgetting months start at 0. new Date(2026, 2, 0) is the end of February, not March.
  • Expecting an error for a day that doesn't exist. Date rolls it into the next month without a word.
  • Writing your own leap-year check. It is easy to miss the century rule. Let Date do it.

Try it yourself

  1. Write lastDayOfMonth(year, month) that returns a Date for the last day, not just the number.
  2. Use daysInMonth to count how many days are left in the month after a given date.
  3. Change safeDate so it returns null for a day that doesn't exist, instead of clamping.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.