Obtener el número de días que tiene un mes

Sencillo script en JavaScript que calcula el numero de días que tiene un mes. Se necesita saber el año para el mes de febrero, para calcular si es un año bisiesto.

// without lookup table
function getMonthDays_A (month, year)
{
if (month === 1)
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
if (month % 2)
return month > 6 ? 31 : 30;
return month > 6 ? 30 : 31;
}
// with lookup table
function getMonthDays_B (month, year)
{
if (month === 1 && year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0))
return 29;
return [31,28,31,30,31,30,31,31,30,31,30,31][month];
}
// mini
function getMonthDays_C (month, year)
{
return (month === 1 && year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) ? 29 : [31,28,31,30,31,30,31,31,30,31,30,31][month];
}
view raw getMonthDays.js hosted with ❤ by GitHub

Creo que esta sería la manera mas sencilla de hacerlo sin almacenar el numero de días que tienen los meses en un array. Por supuesto otra manera de hacerlo seria con una "lookup table".

Comentarios