BugHunt

getMonth() returns the wrong month

getMonth() returns 0 for January and 11 for December, while getDate() returns 1 to 31. Add 1 when displaying a month.

JavaScriptOff-by-one errors

What it means

JavaScript copied the 0-based months from Java's original Date API, and they cannot be changed now. Days of the month are 1-based, so dates come out wrong by exactly one month, and January prints as 0.

Common causes

1. Displaying a month number

The value is an index, not the month people use.

Breaks

`${d.getDate()}/${d.getMonth()}/${d.getFullYear()}`

Works

`${d.getDate()}/${d.getMonth() + 1}/${d.getFullYear()}`

2. Creating a date from a month number

new Date(2024, 3, 1) is April, not March.

Breaks

new Date(2024, 3, 1)   // 1 April

Works

new Date(2024, 3 - 1, 1)   // 1 March

How to find it in your own code

Add 1 when you show a month and subtract 1 when you build a Date from one. Better, let Intl.DateTimeFormat or toLocaleDateString format dates, so you never handle the number yourself.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other common errors