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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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]; | |
} |
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
Publicar un comentario