2012-03-22 15 views
1

以下代碼中的最後一個日誌在Firefox中不起作用。爲什麼?新的日期在字符串的上下文中不起作用在Firefox中

(function() { 

    String.prototype.toDate = function() { 
     return new Date(this); 
    }; 

    console.log(Date.parse("2012-01-31")); 
    console.log(new Date("2012-01-31")); 
    console.log("2012-01-31".toDate()); 

})(); 

要在瀏覽器中測試這一點,我把上面的代碼段到一個文件,並使用下面的HTML。

<!DOCTYPE html> 
<body> 
    <script src="wtf.js"></script> 
</body> 

的NodeJS(v0.4.12):

1327932000000 
Mon, 30 Jan 2012 14:00:00 GMT 
Mon, 30 Jan 2012 14:00:00 GMT 

鉻(17.0.963.79):

1327968000000 
Tue Jan 31 2012 10:00:00 GMT+1000 (EST) 
Tue Jan 31 2012 10:00:00 GMT+1000 (EST) 

火狐(10.0):

1327968000000 
Date {Tue Jan 31 2012 10:00:00 GMT+1000 (EST)} 
Date {Invalid Date} 

回答

0

在Firefox的this String.prototype似乎不是以字符串形式保存字符串。如果你添加到你的方法:

String.prototype.toDate = function() { 
     return new Date(String(this)); 
    }; 

它工作正常。

+0

有趣。 'new String(this)'不起作用,但'String(this)'和'this.toString()'起作用。 – dteoh 2012-03-23 00:49:11

+0

您應該也可以使用'('2012-01-31')。toDate()',但我現在無法測試它。 – RobG 2012-03-23 02:56:08

相關問題