2012-03-07 24 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

相關問題