检测字符串是否可以转换为日期

时间:2012-03-07 16:34:59

标签: javascript datetime date

目前,我正在使用:

var d = new Date("March 7 2012");
document.write(d.getMonth() + 1);

如果日期字符串像No Date那样奇怪,例如:

,该怎么办?
var d = new Date("No Date"); // anything which isn't recognisable as a date
document.write(d.getMonth() + 1);

我得到的输出是NaN

如果出现类似情况,如何显示更好的消息

4 个答案:

答案 0 :(得分:7)

您可以使用NaN

检查该值是否为isNaN
    if (isNaN(d.getMonth())) {
       //value is not a date
    }
    else
    {
       document.write(d.getMonth() + 1);
    }

答案 1 :(得分:0)

使用类似的东西

var d= new Date('No Date');
    var mon=d.getMonth()+1;
    document.write(isNAN(mon)?"No Date": mon);

答案 2 :(得分:0)

你也可以这样做:

Date.isValid = function(date) { 
  return !!Date.parse(date);
};

Date.isValid('fake') // false
Date.isValid('1990-11-15T00:00:00+00:00') // true

答案 3 :(得分:-2)

这似乎有效。

 new Date("Hi") == 'Invalid Date'
相关问题