Get the Number of Days in a Month using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get the Number of Days in a Month #

To get the number of days in a month:

  1. Call the new Date() constructor, passing it 0 for the days.
  2. The method will return the date corresponding to the last day of the month.
  3. Call the getDate() method on the result to get the number of days in the month.
index.js
function getDaysInMonth(year, month) { return new Date(year, month, 0).getDate(); } const date = new Date(); const currentYear = date.getFullYear(); const currentMonth = date.getMonth() + 1; // 👈️ months are 0-based // 👇️ Current Month const daysInCurrentMonth = getDaysInMonth(currentYear, currentMonth); console.log(daysInCurrentMonth); // 👇️ Other Months const daysInJanuary = getDaysInMonth(2025, 1); console.log(daysInJanuary); // 👉️ 31 const daysInSeptember = getDaysInMonth(2025, 9); console.log(daysInSeptember); // 👉️ 30

We passed the following 3 arguments to the new Date() constructor:

  1. The year for which we want to create a Date object
  2. The month index for which we want to create a Date object. Month indexes are zero based - 0 is January and 11 is December.
  3. The day for which to create a Date object. When 0 is used for the days, we get back the last day of the previous month. We use this approach to balance out the zero-based month index.
If you're passing the result of calling getMonth to the function, make sure to add 1 to the month index.
index.js
const date = new Date(); // 👇️ add 1 to get correct value const currentMonth = date.getMonth() + 1;

Passing 0 for the days parameter, allows us to use intuitive month indexes when using the Date constructor.

For example, passing a month index of 2, gives us the last day in February, and not March.

index.js
console.log(new Date(2025, 1, 0)); // 👉️ Fri January 31 2025 console.log(new Date(2025, 2, 0)); // 👉️ Fri Feb 28 2025
This returns an object that represents the last day of the month.

The last step is to call the Date.getDate method. The method returns an integer from 1 to 31, which represents the day of the month for a given date.

Getting the integer representation of the last day of the month is the equivalent of getting the number of days in the month.

Further Reading #

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.