javascript - Detect if string can be converted to date - Stack Overflow

At the moment, i am using:var d = new Date("March 7 2012");document.write(d.getMonth() + 1);

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
Add a ment  | 

4 Answers 4

Reset to default 9

You 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'

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744157613a4560934.html

相关推荐

  • javascript - Detect if string can be converted to date - Stack Overflow

    At the moment, i am using:var d = new Date("March 7 2012");document.write(d.getMonth() + 1);

    9天前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信