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

Detect if string can be converted to date

本文关键字:转换 日期 字符串 是否 检测      更新时间:2023-09-26

目前,我正在使用:

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

如果发生类似情况,我如何显示更好的消息?

您可以使用isNaN:检查该值是否不是NaN

    if (isNaN(d.getMonth())) {
       //value is not a date
    }
    else
    {
       document.write(d.getMonth() + 1);
    }

使用类似的东西

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

您也可以这样做:

Date.isValid = function(date) { 
  return !!Date.parse(date);
};
Date.isValid('fake') // false
Date.isValid('1990-11-15T00:00:00+00:00') // true

这似乎奏效了。

 new Date("Hi") == 'Invalid Date'