Posts Tagged date

How to get the amount of days in an arbitrary month with leapyear in consideration

function daysInMonth( month, year ) {
       var now  = new Date();
       month = month || now.getMonth()+1; //this month as default
       year = year || now.getFullYear();    //this year as default
       return new Date(year, month, 0).getDate();
}
 
//consider January as month 1, February as month 2 ... December 12
 
daysInMonth( 2, 2003 ); //returns 28, not leap-year
daysInMonth( 2, 2004 ); //returns 29, leap-year
daysInMonth( 7, 2009 ); //returns 31
daysInMonth( ); //returns the amount of days in the current month

, , , ,

No Comments