Monday, July 31, 2006

Find out how many days are in a given month (JavaScript)

Often an array is used to figure out how many days there are in a month (and extra work is used to figure out how many days are in February (depending on the leap year)). This method uses the inbuilt Date object, so should be user locale friendly (assuming 12 months in a year). For instance, to find out how many days are in February 2008, you would do: daysInMonth(2008, 2)

function daysInMonth(year, month)
{
 // month is zero based, so take away 1
 month = --month;
 // first day of the following month
 var nextDay;
 // if last month of year, then use first day of following year
 if(month == 11)
 {
  nextDay = new Date(++year, 0);
 }
 // otherwise use next day of current year
 else
 {
  nextDay = new Date(year, ++month);
 }
 // take away a millisecond to get required date
 var requiredDate = new Date(nextDay - 1);
 // return the day
 return requiredDate.getDate();
}

1 comment:

Dave said...

Very slick. Thank you for being so concise.