# Determining the Number of Days in a Month with Javascript

Discussion in 'JavaScript and AJAX' started by pradeep, Jun 13, 2006.

Joined:
Apr 4, 2005
Messages:
1,645
87
Trophy Points:
0
Occupation:
Programmer
Location:
Kolkata, India
Essentially, writing some code to determine the number of days in a given month of a given year with javascript is not the worlds most difficult task. It is the type of exercise that one would expect to be given as a newbie developer during a lab or lecture. The solution normally involves determining if the month is February, an month with 30 days or a month with 31 days, then (if February) checking if the year is a leap year. All these tests add up, however, and add several lines of code to your .js file. They are also unnecessary!

Apparently, the javascript Date function allows you to overflow the day number parameter that you pass, creating a date in the next month. Deliberately overflowing the day parameter and checking how far the resulting date overlaps into the next month is a quick way to tell how many days there were in the queried month. Here is a function that does this:

Code:
```function daysInMonth(iMonth, iYear)
{
return 32 - new Date(iYear, iMonth, 32).getDate();
}
```
N.B.: iMonth is zero based, so 0 represents January, 1 represents February, 2 represents March and 11 represents December. iYear is not zero based, this is the actual calendar year number. (2006 is actually 2006)

Pray that the browser developers know the correct way to determine whether a year is a leap year! (It's more complicated than a simple mod 4 == 0) Here is a quote from Wikipedia's page on leap years: "The Gregorian calendar, the current standard calendar in most of the world, adds a 29th day to February in all years evenly divisible by 4, except for centennial years (those ending in '00'), which receive the extra day only if they are evenly divisible by 400. Thus 1600, 2000 and 2400 are leap years but 1700, 1800, 1900 and 2100 are not."

To test this function, February in the years 2100, 2005, 2004, 2003, 2001, 2000 and 1999 should be checked. All of these should return 28, except for 2004 and 2000.

HTML:
``` <button onclick="alert(daysInMonth(1, 2100));">February 2100