Get number of days in month in JavaScript

Marius
Posts: 55

Get number of days in month in JavaScript

Hello
I want to make a calendar, but I don't know how to calculate the number of days in month, in any year.
How can I get the number of days in any month in a year, taking into account leap years?

Admin
Hello
You can use the daysInMonth() function from this example (month is 1 based):

Code: Select all

//Returns the number of days in a given month (1 - 12) and year
function daysInMonth(month, year){
  return month == 2 ? (year %4 ? 28 : (year %100 ? 29 : (year %400 ? 28 :29))) : ((month -1) %7% 2 ? 30 :31);
}
var nr_days = daysInMonth(2, 2016);
alert(nr_days);  // 29

- If someone needs, in PHP there is the cal_days_in_month() function.

Code: Select all

$nr_days cal_days_in_month(CAL_GREGORIAN82003); // 31 

Adv. Posts: 01

Similar Topics