Search

7/22/2009

Last Day of the Month

Last Day of the Month


function daysInMonth(month,year) {
var ds = String(monthNum+1)+'/0/'+String(yearNum);
var dd = new Date(ds);
return dd.getDate();
}

This code is much shorter than our first example and it works perfectly in some browsers. Unfortunately not all browsers process strings passed into the date constructor the same way. Internet Explorer and Firefox will treat day zero of next month as the last day of the current month and will therefore return the correct number of days so this code appears to work. Unfortunately not all browsers interpret the zero in this way. Opera for example considers a zero to represent the current day of the month and so the function will return today's date rather than the number of days in the requested month.

We can easily fix this and make our code even shorted by passing the year, month, and day into the date constructor as numbers instead of as a US date format string. This format expects month numbers between 0 and 11 instead of 1 and 12 so we don't need to add 1 to get next month as our month field is already one greater.

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

沒有留言: