19

How can I write a JavaScript function that accepts a number from 1 - 12 representing the months of the year, and then returns the number of days in that month?

Taryn East
  • 27,486
  • 9
  • 86
  • 108
Bryan hackett
  • 261
  • 1
  • 2
  • 3

11 Answers11

51
function getDaysInMonth(m, y) {
   return /8|3|5|10/.test(--m)?30:m==1?(!(y%4)&&y%100)||!(y%400)?29:28:31;
}
James
  • 109,676
  • 31
  • 162
  • 175
45

Try this:

function numberOfDays(year, month) {
    var d = new Date(year, month, 0);
    return d.getDate();
}

Because of leap years you need to pass the year too.

Caleb
  • 9,272
  • 38
  • 30
  • 3
    This is almost correct except that as far as Javascript's `Date` objects are concerned, months are indexed from 0-11 and the OP wants to input months indexed from 1-12. You'll have to subtract 1 from the month variable thats passed in if you want my upvote. – Asaph Nov 28 '09 at 00:58
  • 1
    @Asaph: look at the answer again. It's perfect. – Crescent Fresh Nov 28 '09 at 01:43
  • 4
    @Crescent Fresh: Ok, I see what's going on now. The month needs 1 subtracted from it to correct for the zero indexing but then the strategy used is to examine the next month (ie. add 1 to the month, thereby canceling out the subtracted 1) and back off the day (3rd argument to `Date` constructor) by 1, making it the zeroth day of next month which works out to the last day of the current month. So it works. But it's clever. And clever code is unmaintainable code. I would refactor this to something more readable or at the very least add a comment to explain the cleverness. – Asaph Nov 28 '09 at 03:00
  • 3
    @Asaph: "clever" is subjective. The algorithm is sound. About the only negative IMO is it does hit the system clock to do something that can be determined with simple conditionals and math. – Crescent Fresh Nov 28 '09 at 04:02
  • I like this answer, but is there a way to convert it from a Date to a number? – Alexander Ryan Baggett Aug 11 '14 at 10:23
  • 1
    `new Date` is relatively slow compared to even regEx. Much faster results are possible with a combination of binary and boolean maths: http://jsperf.com/days-in-month-perf-test – iCollect.it Ltd Jan 14 '15 at 15:59
  • The above solution is wrong when the day is 0 and if I try to find the name of the months, then month 0 is December (Expected Jan), 1 is Jan, 2 is Feb and 11 is December again. So to get correct behaviour just write +1 after the month. See the comments of the answer below https://stackoverflow.com/a/1184359 – Therii Feb 15 '21 at 19:11
  • for(let a = 0;a<13;a++) { date1= new Date(2021,a,0); date2 = new Date(2021,a, 1) document.write("\n"+ date1.toLocaleString('default', { month: 'long' }) +". " +date2.toLocaleString('default', { month: 'long' }) +" "+date1.getDate() );} – Therii Feb 15 '21 at 19:18
  • Output of above code ===> December. January 31 January. February 31 February. March 28 March. April 31 April. May 30 May. June 31 June. July 30 July. August 31 August. September 31 September. October 30 October. November 31 November. December 30 December. January 31 – Therii Feb 15 '21 at 19:18
27

Thirty days hath September,
April, June, and November;
All the rest have thirty-one,
Excepting February alone,
Which hath twenty-eight days clear,
And twenty-nine in each leap year.

<3 Wikipedia

James
  • 2,626
  • 5
  • 37
  • 51
  • 1
    +1 for link to Wikipedia and great rhyme – MBO Nov 27 '09 at 23:59
  • 15
    I prefer the version which goes "Thirty days hath September, April June and no wonder, All the rest had bread and jam, Except for Grandma, she rides a bicycle." – pavium Nov 28 '09 at 00:00
13

Loved James' answer. Reformatted slightly for those interested.

function getDaysInMonth(m, y)
{
    // months in JavaScript start at 0 so decrement by 1 e.g. 11 = Dec
    --m;

    // if month is Sept, Apr, Jun, Nov return 30 days
    if( /8|3|5|10/.test( m ) ) return 30;

    // if month is not Feb return 31 days
    if( m != 1 ) return 31;

    // To get this far month must be Feb ( 1 )
    // if the year is a leap year then Feb has 29 days
    if( ( y % 4 == 0 && y % 100 != 0 ) || y % 400 == 0 ) return 29;

    // Not a leap year. Feb has 28 days.
    return 28;
}

Fiddle here

Bruno
  • 5,772
  • 1
  • 26
  • 43
  • Regex is relatively slow. Much faster results are possible with a combination of binary and boolean maths: http://jsperf.com/days-in-month-perf-test – iCollect.it Ltd Jan 14 '15 at 15:59
8

Everyone knows that counting Chuck's knuckle sandwich beats mere poetry any day of the week month..

Chuck Norris' Fist. Count the knucle's.

If you can't get that to compile and run (like the poetry), then read on.


Without regex and minus 2 modulo remainder operations, also without leap-year problems or 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 (easily beating James' answer) 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 (again modified to obtain the shortest path).

Note that in AD/BC notation, year 0 AD/BC does not exist: instead year 1 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.)

function daysInMonth(m, y){
  return m===2?y&3||!(y%25)&&y&15?28:29:30+(m+(m>>3)&1);
}
<!-- example for the snippet -->
<input type="text" placeholder="enter year" onblur="
  for( var r='', i=0, y=+this.value
     ; 12>i++
     ; r+= 'Month: ' + i + ' has ' + daysInMonth(i, y) + ' days<br>'
     );
  this.nextSibling.innerHTML=r;
" /><div></div>

Note, months must be 1-based (as the question asked for)!

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.


EDIT (-history):
I lifted my modified mod8 month algo

return(m===2?y&3||!(y%25)&&y&15?28:29:30)+(m+(m>>3)&1);   //algo 1

to the ternary and removed the now un-needed outer parenthesis (good call, TrueBlueAussie):

return m===2?y&3||!(y%25)&&y&15?28:29:30+(m+(m>>3)&1);    //algo 2

After severe testing this turned out to be the fastest algo (thanks TrueBlueAussie for the tests to which I chipped in for the caching jsperf setup). We guess the reason that this is faster then my (shorter and seemingly faster) algo 3 (the magic number bitwise lookup below), is that modern browsers can probably pre-optimise the constant bitshift in m>>3.

I figured.. well.. "and why again didn't I just do?:"

return m===2?y&3||!(y%25)&&y&15?28:29:30+(5546>>m&1);     // algo 3

It uses a a 'magic number' to do a simple bit-wise lookup of offsets:

DNOSAJJMAMFJ* = Months (right to left)
CBA9876543210 = Month === bit position in hex (we never use pos 0: January is 1)
1010110101010 = offset from 30 = binary === 5546 decimal

13 bits is less than 31 bits, so we can safely save another character on the bitshift instead of >>> (as we don't need to force unsigned 32 bit).

That eliminates one memory-call (var m), one addition and one precedence! (and it's one char shorter)

One would think that: obviously these 3 extra optimizations beat my first/second algo (which as TrueBlueAussie commented, was already the fastest)...
But as I already mentioned, it turned out that this (algo 3) is not faster on modern browsers (I know, rather unexpected), we think it is because the engine can no longer optimize the bitshift.
I'll leave it here, maybe one day it will be faster, who knows..

As it turned out my algo 2 was the fastest after-all (except TrueBlueAussie's full 2D array of-course, although that takes quite some more memory and still requires a fast algo to build it client-side), I followed TrueBlueAussie's advice to revert my answer to using my algo 2.

Still I had a blast collaborating and am grateful for the incentive to revisit my answer !

Community
  • 1
  • 1
GitaarLAB
  • 14,536
  • 11
  • 60
  • 80
  • 1
    I see now your algorithm is based on similar boolean + binary maths to my own and both give the exact same results. As yours is *a hair* faster (0.9%) I shall continue to try improve mine. Well done piecing that together :) I did not know about the "mod-8 month" algorithm until this, but based it on raw binary and my son's "knuckle algorithm" from school. – iCollect.it Ltd Jan 15 '15 at 10:43
  • 1
    Using `m + m >> 3` being a tad faster than `(m >> 3) ^ m`, I have managed to tweak a bit more speed out of my code. Cheers for that example :) – iCollect.it Ltd Jan 15 '15 at 11:00
  • After some analysis. I have found your `(5546>>m&1)` is actually slower than `((m + (m >> 3)) & 1)` *in Chrome only*. I guess that operation is optimized in IE. – iCollect.it Ltd Jan 16 '15 at 10:16
  • Here is a head-to-head testbed for any further improvements: http://jsperf.com/days-in-month-head-to-head/3 Mine is faster in Chrome and yours is faster in IE (and everyone hates IE) :) – iCollect.it Ltd Jan 16 '15 at 10:28
  • Another note about the leap year code. Amazingly `y % 4` is actually faster than `y & 3`. Go figure! :) – iCollect.it Ltd Jan 16 '15 at 10:34
  • @TrueBlueAussie: although I believe your test-results, it just makes no sense that `(5546>>m&1)` is actually slower than `((m + (m >> 3)) & 1)`: There is *still* a bitshift and there is still a bitmask. Possibly the bitshift using a constant can be better optimized by chrome (so that it's still faster with the extra precedence, mem-acces/identifier-lookup and addition)? As to the `y % 4` vs `y & 3`: could it be that the 32-bit conversion-step for bitwise is now becoming more noticeable (in Chrome)? – GitaarLAB Jan 16 '15 at 13:44
  • I am guessing that a bit-shift, using a variable for the shift, actually results in a loop (1-12 separate shifts). Have to wonder what other operations are not as fast as they appear :) – iCollect.it Ltd Jan 16 '15 at 13:47
  • @TrueBlueAussie: Lol, and then suddenly in http://jsperf.com/days-in-month-head-to-head/4 'mine' is suddenly a clear winner in chrome and firefox.. – GitaarLAB Jan 16 '15 at 14:23
  • 1
    The most coding fun I have had recently. +1 for being the current fastest (except against my ridiculously memory-inefficient 2-D array solution of course http://jsperf.com/days-in-month-head-to-head/5 :P) I *will* be back! :) – iCollect.it Ltd Jan 16 '15 at 14:42
  • Full credit for pointing me at various solutions, and I've have updated my code including the 25/15 leap year info from http://stackoverflow.com/questions/9852837/leap-year-check-using-bitwise-operators-amazing-speed. Check out perf again: http://jsperf.com/days-in-month-head-to-head/5 **in the lead now** :) – iCollect.it Ltd Jan 16 '15 at 15:20
6

In computer terms, new Date() and regular expression solutions are slow! If you want a super-fast (and super-cryptic) one-liner, try this one (assuming m is in Jan=1 format as per the question):

The only real competition for speed is from @GitaarLab, so I have created a head-to-head JSPerf for us to test on: http://jsperf.com/days-in-month-head-to-head/5

I keep trying different code changes to get the best performance.

Current version

After looking at this related question Leap year check using bitwise operators (amazing speed) and discovering what the 25 & 15 magic number represented, I have come up with this optimized hybrid of answers:

function getDaysInMonth(m, y) {
    return m===2 ? y & 3 || !(y % 25) && y & 15 ? 28 : 29 : 30 + (m +(m >> 3) & 1);
}

JSFiddle: http://jsfiddle.net/TrueBlueAussie/H89X3/22/

JSPerf results: http://jsperf.com/days-in-month-head-to-head/5

For some reason, (m+(m>>3)&1) is more efficient than (5546>>m&1) on almost all browsers.


Previous Versions:

This one removed a single ! test by reversing the values (slight increase):

function getDaysInMonth(m, y) {
    return m === 2 ? (y % 4 || !(y % 100) && (y % 400)) ? 28 : 29 : 30 + (m + (m >> 3) & 1);
}

This one removed any the unnecessary brackets:

function getDaysInMonth2(m, y) {
    return m === 2 ? !(y % 4 || !(y % 100) && (y % 400)) ? 29 : 28 : 30 + (m + (m >> 3) & 1);
}

This one was down to + being a tad faster than XOR (^)

function getDaysInMonth(m, y) {
    return (m === 2) ? (!((y % 4) || (!(y % 100) && (y % 400))) ? 29 : 28) : 30 + ((m + (m >> 3)) & 1);
}

This was my original stab at it:

function getDaysInMonth(m, y) {
    return m == 2 ? (!((y % 4) || (!(y % 100) && (y % 400))) ? 29 : 28) : (30 + ((m >> 3 ^ m) & 1));
}

It works based on my leap year answer here: javascript to find leap year this answer here Leap year check using bitwise operators (amazing speed) as well as the following binary logic.


A quick lesson in binary months:

If you interpret the index of the desired months (Jan = 1) in binary you will notice that months with 31 days either have bit 3 clear and bit 0 set, or bit 3 set and bit 0 clear.

Jan = 1  = 0001 : 31 days
Feb = 2  = 0010
Mar = 3  = 0011 : 31 days
Apr = 4  = 0100
May = 5  = 0101 : 31 days
Jun = 6  = 0110
Jul = 7  = 0111 : 31 days
Aug = 8  = 1000 : 31 days
Sep = 9  = 1001
Oct = 10 = 1010 : 31 days
Nov = 11 = 1011
Dec = 12 = 1100 : 31 days

That means you can shift the value 3 places with >> 3, XOR the bits with the original ^ m and see if the result is 1 or 0 in bit position 0 using & 1. Note: It turns out + is slightly faster than XOR (^) and (m >> 3) + m gives the same result in bit 0.

JSPerf results: http://jsperf.com/days-in-month-perf-test/6 (23 times faster than the accepted answer).


Update: I ran a comparison of the top two answers + latest (@James, @Caleb & @GitaarLAB) against this one to ensure they gave consistent results and all 4 return the same values for all months in all years from year 1 to year 4000: http://jsfiddle.net/TrueBlueAussie/8Lmpnpz4/6/. Year 0 is the same for all except @Caleb.

Another update:

If absolute speed were the only goal, and you do not mind wasting memory, then storing the results for a given span of years, in a 2-dimensional table is probably the fastest possible way:

function DIM(m, y) { //TrueBlueAussie
    return m===2?(y%4||!(y%100)&&(y%400))?28:29:30+(m+(m>>3)&1);
}
array = new Array(4000);
for (var y = 1; y < 4000; y++){
    array[y] = [];
    for (var m = 1; m < 13; m++)
    {
        array[y][m] = DIM(m, y);
    }
}

// This just does a lookup into the primed table - wasteful, but fast
function getDaysInMonth2(m, y){
    return array[y][m];
}

JSPerf: http://jsperf.com/days-in-month-head-to-head/5

Community
  • 1
  • 1
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • Wait a second.. so now you ended up (answer v10) with my modified mod8 month-algoritm (identical) which you lifted to the first ternary (which is a good call! I'm copying that thank you) and the *slower* leap-year algorithm. You should be able to get another bonus by using the strictly equal operator `m===2` like in my answer, thereby informing the engine that we don't need type-coercion! Thanks for the perf and the fiddle! Good job on explaining the mod8 algo, I figured anyone could find it on wikipedia which is why I left that out and just named it. Check my faster *new* algo! – GitaarLAB Jan 16 '15 at 04:07
  • @GitaarLAB: Thanks for suggesting the `===`. Not sure why you assume my leap year algorithm is slower than yours. Even without your clever shifted bit-mask mine is faster in Chrome: http://jsperf.com/days-in-month-perf-test/6 (but not in IE) :) – iCollect.it Ltd Jan 16 '15 at 10:17
  • As you commented to my answer: *Amazingly `y % 4` is actually faster than `y & 3` Go figure! :)* (which I assume was in chrome). That's why I (also from experience: it defensively *used* to be faster) assumed it was faster. Seems we are both a bit baffled about that in retrospect.. In the end, most perf-tests end this way (due to different engines). Personally I usually pick the best average performer (taking into account codesize and often older browsers that I want/need/must support). I also often seen something being faster in browser X ver Y and suddenly X ver Z is slowest.. – GitaarLAB Jan 16 '15 at 12:56
  • @GitaarLAB: Actually `y % 4` is actually faster than `y & 3` on IE too (at least nowadays). You might want to try speeding up your own using that. Chrome is almost double the speed of IE anyway for any of our versions of this algorithm :) – iCollect.it Ltd Jan 16 '15 at 13:14
  • I just clocked some tests on http://jsperf.com/days-in-month-head-to-head/3. IE7 was slightly faster for 'mine', FF28 was more clearly faster for 'mine'. Then I created http://jsperf.com/days-in-month-head-to-head/4. Firefox Suddenly gave me more than *double* the number of tests and also a much larger speed-difference. IE7 on the other hand.. got slower and suddenly yours consistently wins. And yes, I was indeed just thinking.. we are testing to much at once, we should probably separate leap-year and month alone. Another thing is probably boolconversions: speed differs wildly amongst browsers – GitaarLAB Jan 16 '15 at 13:54
  • I think parsing the bit-mask value probably slowed yours down before, so lifting them to setup would have helped on the 100 test runs it does. I will start testing the leap year vs day parts as you suggest. Must be a little more speed to tweak out of this puppy yet (most fun I've had in ages) :) – iCollect.it Ltd Jan 16 '15 at 14:08
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/68963/discussion-between-gitaarlab-and-trueblueaussie). – GitaarLAB Jan 16 '15 at 14:13
  • Uhm.. you do realize that your current answer (ver 17) is now *exactly* my algo 2 (without the outer wrapping parenthesis)? including my mod-8 algo? And didn't you say your original leap-year algo using `%` was faster and asked me why I thought your leapyear algo was slower? – GitaarLAB Jan 16 '15 at 15:34
  • 1
    Once I understood the 15 and 25 from http://stackoverflow.com/questions/9852837/leap-year-check-using-bitwise-operators-amazing-speed it naturally followed I would have to use it. As the perf is now pre-compiling I found the `& 3` became faster than `% 4` (tried all combinations on both that and the `& 15`). I had not reviewed the originals, but yes, you probably should have stuck with your earlier version. If I come up with any alternative that is faster I will add that too. Full credit to your clever bit mask, but that is one step too far in the wrong [speed] direction. – iCollect.it Ltd Jan 16 '15 at 15:42
  • Apologies that it does now wind up nearly the same (but I credited every source as I went, including yours). All roads apparently *do* lead to Rome :) – iCollect.it Ltd Jan 16 '15 at 15:43
  • Well, I always linked to that answer explaining the leap-year algo (that I modded for this and you now also use. It *feels* a bit unfair to now also call `(m+(m>>3)&1)` yours. So currently, the only thing that could be improved on my original answer was lifting my mod8 algo to the ternary (as in my [first comment](http://stackoverflow.com/questions/1810984/number-of-days-in-any-month/27946635?noredirect=1#comment44346595_27946635) and removing the now un-needed wrapping outer-parentesis. – GitaarLAB Jan 16 '15 at 15:53
  • Apologies for that reference. I can see now how that may read and will adjust it. It is pretty clear how my code evolved as I show it step-by-step. No plagiarism was intended. It just happens that's where all the information leads. Well done on finding the same info first :) – iCollect.it Ltd Jan 16 '15 at 16:03
  • I presume that Javascript treats boolean results as 0 or 1, similar to C and C++; if so, you could try replacing the ternary `y & 3 || !(y % 25) && y & 15 ? 28 : 29` with `29 - (y & 3 || !(y % 25) && y & 15)`. – Mark Ransom Jan 16 '15 at 16:08
  • @Mark Ransom: No, it doesn't unfortunately. The numbers can be interpreted as boolean values (`0` and `not 0`), but they retain their numeric/bit values so can't be treated as 1 or 0. – iCollect.it Ltd Jan 16 '15 at 16:10
  • @TrueBlueAussie: thanks for that edit. You were already crediting, so while I reverted and updated my answer, I already assumed you'd correct that. No harm done, apologies accepted etc. etc. ! `:)` With that same trust I also already setup http://jsperf.com/days-in-month-head-to-head/8 for the exact alg 2 and 3. Side-note, I still find all the different results in jsperf somewhat amazing, but I *think* we got our later perf setups right: the only thing that changed was the passed function. Have a great day! – GitaarLAB Jan 16 '15 at 17:39
  • @GitaarLAB: Those new results are hard to believe. I would not have expected that big a difference in all browsers (did not see 20% in previous setup, more like 1%) :) – iCollect.it Ltd Jan 16 '15 at 17:50
  • I know, I noticed that too (although in previous setups I did see larger differences than 1 %, like FF in head-to-head/4). I triple-checked both functions (plugged them into your fiddle) copy-paste straight from the perf. I also tested the `tst` function and the functions in the perf. I even looked at it side-ways... – GitaarLAB Jan 16 '15 at 18:59
1

In the spirit of not doing your homework for you, I present a version in POVRay (sorry, not JS) I did many years ago.

In POVRay, there are no boolean variables. The method I came up with was to create a polynomial in 'm' which gave an answer > 0 for months with 31 days and < 0 for months with 30 days.

#declare m0 = (m-0.5)*(m-1.5)*(m-2.5)*(m-3.5)*(m-4.5)*(m-5.5);
#declare m0 = m0*(m-6.5)*(m-8.5)*(m-9.5)*(m-10.5)*(m-11.5);
#if (m0 > 0)
  #declare maxdays = 31;
#else
  #declare maxdays = 30;
#end

The tricky part is to decide when the year is a leap year. This is the full test for leap years. Most people are aware of the 4-year rule, and since 2000, some know about the 100 and 400 year rules, there is no 4000 year rule.

#declare LEAPYEAR = 2.0;
#if (mod(YEAR,4.0)=0)
  #declare LEAPYEAR = 1.0;
  #if (mod(YEAR,100.0)=0)
    #declare LEAPYEAR = 2.0;
  #end
  #if (mod(YEAR,400.0)=0
    #declare LEAPYEAR = 1.0;
  #end
#end
#if (MONTH = 2.0)
  #declare maxdays = maxdays - LEAPYEAR;
#end
#if (DAY > maxdays)
  #declare MONTH = MONTH + 1;
  #declare DAY = DAY - maxdays;
#end
#if (MONTH > 12)
  #declare YEAR = YEAR + 1;
  #declare MONTH = MONTH - 12;
#end
pavium
  • 14,808
  • 4
  • 33
  • 50
1

Loved James' answer as well as Bruno's explanation of it. However, got annoyed at the overly cryptic nature of the solution. So here is the same solution but cleaned of any unnecessary over encryption.

function getDaysInMonth(m, y) {
   return /4|6|9|11/.test(m)?30:m==2?(!(y%4)&&y%100)||!(y%400)?29:28:31;
}

Specifics:

  1. Seems there's no need to decrease month - javascript has nothing to do with it, since we only use it for comparison, so I used the real month numbers for clarity.

  2. Why write the number of april, june, september and november out of order? That's just confusing.

  3. *Optionally, we can increase the month (++m) to get a version that accepts (new Date()).getMonth() as input

tutuDajuju
  • 10,307
  • 6
  • 65
  • 88
  • 1
    Regex is relatively slow. Much faster results are possible with a combination of binary and boolean maths: http://jsperf.com/days-in-month-perf-test – iCollect.it Ltd Jan 14 '15 at 16:00
  • @TrueBlueAussie agreed. For a scenario where 300 such operations per second are just not enough, an optimized solution (though slightly less readable) should prove to be invaluable! Thanks for the benchmark. – tutuDajuju Jan 15 '15 at 08:32
1

I came across this question whilst playing with a C/C++/C# hobby project. So, although this answer may not be pertinent to the OP, the remainder of the answers/comments seem to concern JavaScript "golf"; which is a bit of a black art due to the vagaries of JS JIT, but fun nonetheless.

Standing on the shoulders of GitaarLAB, TrueBlueAussie, et al, I propose:

return m===2?y&3||!(y%25)&&y&15?28:29:30|(m+(m>>3));
Ian Taylor
  • 11
  • 1
0

try this:

function DaysinMonth(aDate)  {
    return aDate.setMonth(aDate.getMonth()+1, 0).getDate();
}    
Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
  • This is the best answer for me (+1). Only, getDate() will return epoch milliseconds. So you should convert it to Date. This works better: var date = new Date(); return (new Date(date.setMonth(date.getMonth() + 1, 0))).getDate(); – Onur Yıldırım May 02 '12 at 01:17
0

Try this:

function daysInMonth(year, month) {
    var isLeap = ( (!(year % 4)) && ( (year % 100) || (!(year % 400)) ) );

    if (month == 2)
        return (isLeap) ? 29 : 28;
    return 30 + (month % 2);
}