Borislav Hadzhiev
Sun Oct 24 2021·2 min read
Photo by Hernan Sanchez
To get the number of days in the current month:
Use the new Date()
constructor to get a date object, that corresponds to
the last day in the current month.
Call the getDate()
method to get an integer representing the last day of
the month.
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:
0
is January
and 11
is December. This is why we added 1
to the result.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.
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.
console.log(new Date(2025, 1, 0)); // 👉️ Fri January 31 2025 console.log(new Date(2025, 2, 0)); // 👉️ Fri Feb 28 2025
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.