Get the Number of Days in a Month using JavaScript

avatar

Borislav Hadzhiev

Sun Oct 24 20212 min read

banner

Photo by Linas Bam

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 as the day.
  2. This returns 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 parameters 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 as the day, 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 from 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 as 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 for 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 in 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee