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();
}
In a single line:
Considering leap years:
Some answers (also on other questions) had leap-year problems or used the Date-object. Although javascript's
Date object
covers approximately 285616 years (100,000,000 days) on either side of January 1 1970, I was fed up with all kinds of unexpected date inconsistencies across different browsers (most notably year 0 to 99). I was also curious how to calculate it.So I wrote a simple and above all, small algorithm to calculate the correct (Proleptic Gregorian / Astronomical / ISO 8601:2004 (clause 4.3.2.1), so year
0
exists and is a leap year and negative years are supported) number of day's for a given month and year.It uses the short-circuit bitmask-modulo leapYear algorithm (slightly modified for js) and common mod-8 month algorithm.
Note that in
AD/BC
notation, year 0 AD/BC does not exist: instead year1 BC
is the leap-year!IF you need to account for BC notation then simply subtract one year of the (otherwise positive) year-value first!! (Or subtract the year from
1
for further year-calculations.)Note, months must be 1-based!
Note, this is a different algorithm then the magic number lookup I used in my Javascript calculate the day of the year (1 - 366) answer, because here the extra branch for the leap-year is only needed for February.
If you want the number of days in the current month of a Date object, consider the following method:
Then you can run it like this:
To take away confusion I would probably make the month string based as it is currently 1 based.