Skip to content
Advertisement

What is the best way to determine the number of days in a month with JavaScript?

I’ve been using this function but I’d like to know what’s the most efficient and accurate way to get it.

function daysInMonth(iMonth, iYear) {
   return 32 - new Date(iYear, iMonth, 32).getDate();
}

Advertisement

Answer

function daysInMonth (month, year) { // Use 1 for January, 2 for February, etc.
  return new Date(year, month, 0).getDate();
}

console.log(daysInMonth(2, 1999)); // February in a non-leap year.
console.log(daysInMonth(2, 2000)); // February in a leap year.

Day 0 is the last day in the previous month. Because the month constructor is 0-based, this works nicely. A bit of a hack, but that’s basically what you’re doing by subtracting 32.

See more : Number of days in the current month

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement