Date.getMonth() returns wrong month in JavaScript [Solved]

avatar

Borislav Hadzhiev

Last updated: Jan 23, 2022

banner

Photo from Unsplash

Date.getMonth() returns wrong month in JavaScript [Solved] #

To get the correct return value from Date.getMonth(), add 1 to the result, e.g. date.getMonth() + 1. The getMonth method returns a zero-based number between 0 and 11, where 0 is January and 11 is December.

index.js
const date = new Date('2022-04-24'); console.log(date.getMonth()); // 👉️ 3 console.log(date.getMonth() + 1); // 👉️ 4

We used the Date() constructor to create a date for the 24th of April, 2022.

Calling the getMonth method on the date returns a value of 3, even though April is the fourth month.

This is because the getMonth method returns a zero-based number between 0 and 11. For example, January is 0, February is 1, March is 2, etc.

If you need to get a one-based value for the month, simply add 1 to the result.

index.js
const date = new Date('2022-04-24'); console.log(date.getMonth() + 1); // 👉️ 4

When passing multiple, comma-separated parameters to the Date() constructor to create a Date object, you should pass a zero-based value for the month.

index.js
const date = new Date(2022, 0, 24, 9, 30, 16); // 👇️ Mon Jan 24 2022 09:30:16 console.log(date);

The parameters we passed to the Date() constructor are the year, month (January = 0, February = 1, etc), day of the month, hour, minutes, seconds.

The Date() constructor expects the month as a zero-based value when passing multiple, comma-separated parameters.

If you need to get the name of the month, you can use the toLocaleString method.

index.js
const date = new Date(2022, 0, 24, 9, 30, 16); // 👇️ Mon Jan 24 2022 09:30:16 console.log(date); const name = date.toLocaleString('default', { month: 'long', }); console.log(name); // 👉️ "January"

We passed the following parameters to the toLocaleString method:

  1. the locale - e.g. en-US or de-DE, in which language the name of the month should be returned. By specifying default, it can vary based on the user's browser preferences.
  2. the options object - we set the month setting to long to get the full name of the month. Other possible values are short and narrow.
index.js
const date = new Date(2022, 0, 24, 9, 30, 16); // 👇️ January console.log(date.toLocaleString('en-US', {month: 'long'})); // 👇️ Jan console.log(date.toLocaleString('en-US', {month: 'short'})); // 👇️ J console.log(date.toLocaleString('en-US', {month: 'narrow'}));

The examples show the output from using different values for the month property on the options object.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.