JavaScript to Get Number of Days in a Month
At work recently the need came up to determine the number of days in a month for a given month and year. This can be accomplished by creating a date object for the given month and year. Then do a while loop. In each iteration of the loop, set the day of the month, starting with 29, which is one more than the fewest days that can occur in a month. After setting the day, check if setting that day changed the month. If it did, then the number of days has been found. Otherwise, the loop iterates again.
For example, for September of 2007, the loop would use setDate() to set a date for September 29th. After doing this, the month would still be 8 (JavaScript dates are zero-relative). The loop would run again. setDate() would set the 30th and the month would still be 8. The loop would run again. setDate() would set the 31st. Since there is no 31st in September, setDate() actually sets October 1st, thus making the month 9. Since the month has changed, we know there are 30 days in September.
Code:
var intMonth = 7;//given month
var intYear = 2007;//given year
var dteMonth = new Date(intYear,intMonth);//
var intDaysInMonth = 28;//the fewest number of days in a month
var blnDateFound = false;//Set a variable to check on the while loop
while (!blnDateFound)
{
dteMonth.setDate(intDaysInMonth+1);//create the next possible day
var intNewMonth = dteMonth.getMonth();//new month date
if (intNewMonth != intMonth)//if the month has changed
blnDateFound = true;
else
intDaysInMonth++;
}
document.write(intDaysInMonth);
August 14, 2007 at 12:51 pm
Yes, because the setDate function is internal to JavaScript that is already taken care of. For example, in 2007 if you add 1 day from Feb. 28th, the next day is March 1st and you know the date has changed. In 2008, however, adding one day to Feb. 28th, results in Feb. 29th and the month has not changed.
April 11, 2009 at 11:17 am
Thanks for this valuable little piece of code. I used it in the website i’m developing for my workplace in order to calculate time intervals for product offers.