At the moment, i am using:
var d = new Date("March 7 2012");
document.write(d.getMonth() + 1);
What if the date string is something weird like No Date
i.e:
var d = new Date("No Date"); // anything which isn't recognisable as a date
document.write(d.getMonth() + 1);
Here the output I get is NaN
How do I display a better message if something like this happens
At the moment, i am using:
var d = new Date("March 7 2012");
document.write(d.getMonth() + 1);
What if the date string is something weird like No Date
i.e:
var d = new Date("No Date"); // anything which isn't recognisable as a date
document.write(d.getMonth() + 1);
Here the output I get is NaN
How do I display a better message if something like this happens
Share Improve this question asked Mar 7, 2012 at 16:34 oshirowanenoshirowanen 16k83 gold badges205 silver badges357 bronze badges 1- possible duplicate of Detecting an "invalid date" Date instance in JavaScript – Mike Christensen Commented Mar 7, 2012 at 16:40
4 Answers
Reset to default 9You can check that the value is not NaN
by using isNaN
:
if (isNaN(d.getMonth())) {
//value is not a date
}
else
{
document.write(d.getMonth() + 1);
}
use somthing like this
var d= new Date('No Date');
var mon=d.getMonth()+1;
document.write(isNAN(mon)?"No Date": mon);
You can also do it like this:
Date.isValid = function(date) {
return !!Date.parse(date);
};
Date.isValid('fake') // false
Date.isValid('1990-11-15T00:00:00+00:00') // true
This seemed to work.
new Date("Hi") == 'Invalid Date'