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();
}
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();
}
With moment.js you can use daysInMonth() method:
If you call this function often, it may be useful to cache the value for better performance.
Here is caching version of FlySwat's answer:
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.
Here is goes
One-liner direct computation (no Date object):
Variation with 0-based months:
Perhaps not the most elegant solution, but easy to understand and maintain; and, it's battle-tested.