#49 · Strings and dates

Find the bug · #49 · Strings and dates Easy JavaScript

December invoices say month 11

Invoice dates are a month behind, and January shows as month 00.

On this page

The report

Bug report

Invoices show their date as DD/MM/YYYY. A Christmas invoice is dated 25/11/2026, and a New Year one 01/00/2027.

The code

Read it first: what should it do? Then click the line where you think the bug is.

JavaScriptClick the line you think is wrong
// Formats a date as DD/MM/YYYY for invoices.
function formatDate(d) {
  const day = String(d.getDate()).padStart(2, '0');
  const month = String(d.getMonth()).padStart(2, '0');
  return day + '/' + month + '/' + d.getFullYear();
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
console.log(formatDate(new Date(2026, 11, 25)));
console.log(formatDate(new Date(2027, 0, 1)));

It prints

25/11/2026
01/00/2027

It should print

25/12/2026
01/01/2027
Show the answer: the bug, the fix, and how you’d find it

The bug (line 4)

Line 4 uses getMonth(), which counts months from zero: January is 0 and December is 11. Days (getDate) start at 1, so the two don’t match, and every invoice is a month behind. Add 1.

The fix

1// Formats a date as DD/MM/YYYY for invoices.2function formatDate(d) {3  const day = String(d.getDate()).padStart(2, '0');4  const month = String(d.getMonth()).padStart(2, '0');4  const month = String(d.getMonth() + 1).padStart(2, '0');5  return day + '/' + month + '/' + d.getFullYear();6}

How you’d find it

  1. Reproduce with the two reported dates: December comes out as 11, January as 00.
  2. Month 00 can’t come from a 1-based count, so the months are 0-based. Check the docs for getMonth: 0 to 11.
  3. Look at the other fields too: getDate is 1-based, getFullYear is the real year. Only the month needs the + 1.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

assert.equal(formatDate(new Date(2026, 11, 25)), '25/12/2026');
assert.equal(formatDate(new Date(2027, 0, 1)), '01/01/2027');

Where else this bites

  • new Date(2026, 12, 1) is January 2027, not December.
  • Java’s old Calendar.MONTH is 0-based too; java.time fixed it.
Your progress stays on this device.