2016-02-04 34 views
0

在I.E. 11,在控制檯窗口中,如果我輸入new Date().toLocaleString(),我會得到類似「2/4/2016 9:12:05 AM」的內容。但是,如果我添加.length,則得到32.該字符串是19個「可讀」字符,那麼32是怎麼回事,有沒有我可以調用的選項會給我一個長度爲19的字符串?JavaScript新日期()。toLocaleString()長度

如果我輸入new Date(new Date().toLocaleString()),我得到[日期]無效日期,而如果我輸入new Date(new Date("2/4/2016 9:12:05 AM")),我會得到一個合法的日期。

我的語言環境是「en-US」。

+0

'的console.log(新的日期()的toLocaleString()分裂( 「」)地圖(函數(C){返回c.charCodeAt(0);}))' – Pointy

+0

此外,適用什麼樣的語言環境到你正在做的測試? – Pointy

+0

en-US(更新後的問題) –

回答

0

您正在使用整個字符串的長度。 在這種情況下這個函數返回的是: Thu Feb 04 2016 17:28:09 GMT + 0200(FLE標準時間)< - 32個字符。 嘗試獲取新日期作爲變量並使用它。

var example = new Date();

+0

函數在您的語言環境中返回的內容與在OP的語言環境中返回的內容不一定相同。 – Pointy

+0

正確,但格式將始終相同。 *如果沒有附加方法 new Date();將以這種格式返回您的本地時間和日期「Thu Feb 04 2016 17:28:09 GMT + 0200」 –

+0

問題不在於新的Date()返回的內容,而是toLocaleString()返回的內容。 –

0

這也發生在IE11上。我遇到了同樣的問題,通過使用下面的日期來修復它,這樣你就不會看到任何看不見的空字符。

var cleanDate = (new Date()).toISOString(); 

這是針對您的問題的解決方案,如果您不想使用上述獲取日期的方法。

//Custom extension method to replace all found value. 
String.prototype.replaceAll = function(find, replace) { 
var target = this; 
    return target.split(find).join(replace); 
}; 
//Find there is invisible empty character 
var emptyCode = (new Date()).toLocaleString().charCodeAt(0); 
var cleanDate = undefined; 
if(emptyCode === 8206) 
{ 
    //Remove all invisiable empty characters 
    cleanDate =(new Date()).toLocaleString().replaceAll(String.fromCharCode(emptyCode),''); 
} 

擴展方法可以從下面的文章中找到。 How to replace all occurrences of a string in JavaScript?