Proper date comparison in #JavaScript

If you want to check if some variable contains valid date in JavaScript, this is the way that works properly in all cases:

isValidDate: function(d) {
    if ( Object.prototype.toString.call(d) === "[object Date]" ) {
        // it is a date, but still it could be 'Invalid date' which could make trouble
        if ( isNaN( d.getTime() ) ) {
            // date is not valid
            return false;
        } else {
            // date is valid
            return true;
        }
    } else {
        // not a date
        return false;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s