oshirowanen oshirowanen - 3 years ago 129
Javascript Question

Detect if string can be converted to date

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

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

How do I display a better message if something like this happens

Answer Source

You can check that the value is not NaN by using isNaN:

    if (isNaN(d.getMonth())) {
       //value is not a date
       document.write(d.getMonth() + 1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download