Get the number of days in a month with Javascript

Posted in Javascript -

This post shows how to get the number of days in a month using Javascript by passing the month and year to a function.

Javascript function to get days in month

A Javascript function to do this is:

function daysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
}

The month passed in is 1 for January, 2 for February and so on through to 12 for December.

The way the above code works is that the month passed to the Date constructor is actually 0 based (i.e. 0 is January, 1 is February etc) so it is in effect creating a date for the day 0 of the next month. Because day 0 equates to the last day of the previous month the number returned is effectively the number of days for the month we want.

To illustrate this working:

for(var  i = 1; i < 13; i++) {
    document.write(daysInMonth(i, 2009) + '<br />');
}

The output from the above is this:

31
28
31
30
31
30
31
31
30
31
30
31

 And to get the days in the month for February over a few years:

for(var  i = 2000; i < 2011; i++) {
    document.write(i + ': ' + daysInMonth(2, i) + '<br />');
}

And the result:

2000: 29
2001: 28
2002: 28
2003: 28
2004: 29
2005: 28
2006: 28
2007: 28
2008: 29
2009: 28
2010: 28


Related posts:


Comments