TryBugHunt

getMonth() returns the wrong month

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

JavaScriptPattern: Off-by-one errors

How do I fix getMonth() returns the wrong month?

In JavaScript, getMonth() returns 0 for January and 11 for December, so displayed months are one too low. Add 1 when showing it: d.getMonth() + 1. When building a date, subtract 1: new Date(2024, 3 - 1, 1) is 1 March. getDate() is not affected, it already returns 1 to 31.

  1. 1. Displayed month numbersLook for getMonth() in strings or labels without + 1 after it.
  2. 2. new Date(y, m, d)The month argument is 0-based too. new Date(2024, 3, 1) is April, not March.
  3. 3. Let Intl format itUse toLocaleDateString() or Intl.DateTimeFormat so you never handle the month number yourself.

What does getMonth() returns the wrong month mean?

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.

Why does getMonth() returns the wrong month happen?

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.

Practise off-by-one errors

None of the challenges raises this exact error yet. These practise the same kind of bug.

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.

Related error guides

View all off-by-one errors →