2012-03-07 29 views
1

目前,我使用:检测,如果字符串可以转换成日期

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

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

+0

可能重复(http://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript) – 2012-03-07 16:40:26

回答

6

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

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

使用的财产以后这样

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

你也可以做这样的:

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

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

这似乎工作。的[在JavaScript中检测的 “无效的日期” Date实例]

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

反对,因为这不起作用?反对票,因为它一直不准确?或者仅仅是因为你想投票选一个呢? – mphollas 2017-07-25 23:43:01