[Solved-6 Solutions] Detecting an “invalid date” Date instance in JavaScript - javascript tutorial
Problem:
How to detect an “invalid date” Date instance in JavaScript?
Solution 1:
The Simplest way is comparing the converted date to validate
function validate_date(y,m,d)
{
var ndate = new Date(y,m-1,d);
var con_date =
""+ndate.getFullYear() + (ndate.getMonth()+1) + ndate.getDate(); //converting the date
var gdate = "" + y + m + d; //given date
return ( gdate == con_date); //return true if date is valid
}
Solution 2:
var d = new Date("foo");
console.log(d.toString()); // shows 'Invalid Date'
console.log(typeof d); // shows 'object'
console.log(d instanceof Date); // shows 'true'
Read Also
The right json Date FormatSolution 3:
if ( Object.prototype.toString.call(d) === "[object Date]" ) {
// it is a date
if ( isNaN( d.getTime() ) ) { // d.valueOf() could also work
// date is not valid
}
else {
// date is valid
}
}
else {
// not a date
}
Solution 4:
Instead of using "new Date()" we should use:
var timestamp=Date.parse('foo')
if (isNaN(timestamp)==false)
{
var d=new Date(timestamp);
}
Date.parse()
returns a timestamp
Read Also
Javascript Date FormattingSolution 5:
- We can check the validity of a
Date
objectd
d instanceof Date && isFinite(d)
- To avoid cross-frame issues, we could replace the instanceof check with
Object.prototype.toString.call(d) === '[object Date]'
Solution 6:
Implementation
Date.prototype.isValid = function () {
// An invalid date object returns NaN for getTime() and NaN is the only
// object not strictly equal to itself.
return this.getTime() === this.getTime();
};
Usage
var d = new Date("lol");
console.log(d.isValid()); // false
d = new Date("2012/09/11");
console.log(d.isValid()); // true