roosteronacid roosteronacid - 1 month ago 6
Javascript Question

Validate number of days in a given month

Performance is of the utmost importance on this one guys... This thing needs to be lightning fast!






How would you validate the number of days in a given month?

My first thought was to make an array containing the days of a given month, with the index representing the month:

var daysInMonth = [
31, // January
28, // February
31, // March
etc.
];


And then do something along the lines of:

function validateDaysInMonth(days, month)
{
if (days < 1 || days > daysInMonth[month]) throw new Error("Frack!");
}


But... What about leap years? How can I implement checking for leap years and keep the function running relatively fast?






Update: I'd like you guys to show me some code which does the days in month- leap year validation.

Here's the flowchart describing the logic used today:


Answer
function daysInMonth(m, y) { // m is 0 indexed: 0-11
    switch (m) {
        case 1 :
            return (y % 4 == 0 && y % 100) || y % 400 == 0 ? 29 : 28;
        case 8 : case 3 : case 5 : case 10 :
            return 30;
        default :
            return 31
    }
}

function isValid(d, m, y) {
    return m >= 0 && m < 12 && d >= 0 && d < daysInMonth(m, y);
}