最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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'
发布评论

评论列表(0)

  1. 暂无评论