Checking dates using JavaScript

JavaScript has a very friendly Date() object. You can pass pretty much any nonsensical string to it and it will try to return you a sensible date object. For example, you can try to initiate a leap day on a non-leap year: new Date('2005/02/29'). The date object that is returned will actually represent the 1st of May. You can push it even further by asking for April 69, which will return the 8th of June.

This can be put to good use if you want to validate a date, especially if it comes from user input. One of the easiest ways to guarantee the validity of a date is to pass it through the Date() constructor and compare the result to the original:

function checkdate(iDay, iMonth, iYear) {
    var sDate = iYear + '/' + iMonth + '/' + iDay;
    var oDate = new Date(sDate);
    return (iDay == oDate.getDate() 
        && iMonth == oDate.getMonth() + 1);
}

alert(checkdate(29,02,2004)); // true - leap year
alert(checkdate(29,02,2003)); // false - no leap year

Have something to say about this post? Share your thoughts!