Validate number of days in a given month

I've been doing this using the Date object (assuming it's compiled, and hence blindingly fast compared to scripting).

The trick is that if you enter a too high number for the date part, the Date object wraps over into the next month. So:

var year = 2009;
var month = 1;
var date = 29;

var presumedDate = new Date(year, month, date);

if (presumedDate.getDate() != date)
    WScript.Echo("Invalid date");
else
    WScript.Echo("Valid date");

This will echo "Invalid date" because presumedDate is actually March 1st.

This leaves all the trouble of leap years etc to the Date object, where I don't have to worry about it.

Neat trick, eh? Dirty, but that's scripting for you...


This will not perform as well as the accepted answer. I threw this in here because I think it is the simplest code. Most people would not need to optimize this function.

function validateDaysInMonth(year, month, day)
{
    if (day < 1 || day > 31 || (new Date(year, month, day)).getMonth() != month)
        throw new Error("Frack!");
}

It takes advantage of the fact that the javascript Date constructor will perform date arithmetic on dates that are out of range, e.g., if you do:

var year = 2001; //not a leap year!
var month = 1 //February
var day = 29; //not a valid date for this year
new Date(year, month, day);

the object will return Mar 1st, 2001 as the date.


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);
}

Tags:

Javascript