Get the Number of Days in the Current Month in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 24 20212 min read

Get the Number of Days in the Current Month #

To get the number of days in the current month:

  1. Use the new Date() constructor to get a date object, that corresponds to the last day in the current month.

  2. Call the getDate() method to get an integer representing the last day of the month.

index.js
function getDaysInCurrentMonth() { const date = new Date(); return new Date( date.getFullYear(), date.getMonth() + 1, 0 ).getDate(); } const result = getDaysInCurrentMonth(); console.log(result);

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

  1. The current year
  2. The current month index. Month indexes are zero based - 0 is January and 11 is December. This is why we added 1 to the result.
  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.

It's quite confusing but the getMonth method returns a zero-based index.

index.js
const date = new Date('January 04, 2025 05:24:07'); console.log(date.getMonth()); // ๐Ÿ‘‰๏ธ 0

To balance this out, we pass 0 to the days parameter to get the last day of the prior month.

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
In the function, the new Date() constructor returns an object representing the last day of the current 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 current 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