2012-08-22 48 views
1

可能重複:
Help parsing ISO 8601 date in Javascript轉換JSON日期字符串到正確的Date對象

我認爲這應該是很簡單的,但變成了令人驚訝的乏味。

從WEB API,我通過AJAX接收selected對象,其屬性之一是InspectionDate日期時間字符串如2012-05-14T00:00:00

在JavaScript中,我使用以下代碼具有正確的日期對象

selected.JsInspectionDate = new Date(selected.InspectionDate); 

但JsInspectionDate顯示

2012/05/14 00:00 in firefox, 
2012/05/13 20:00 in chrome and 
NAN in IE9 

2012-05-14T00:00:00.

有人能告訴我爲什麼會出現這個問題嗎?以及如何解決這個問題?我只想在Firefox中顯示所有瀏覽器。

+0

看起來像一個時區的問題。 4小時不同,你住在東海岸嗎? –

+0

請參閱:http://stackoverflow.com/q/498578/220060 – nalply

+0

@MikeRobinson是我在東海岸時區 –

回答

2

這樣做:

new Date(selected.InspectionDate + "Z") 

理由:你的日期是在ISO 8601形式。時區指示符如"Z",這是UTC的一個很短的工作。

注意! IE可能不理解ISO 8601日期。所有投注都關閉。在這種情況下,最好使用datejs

+0

是啊,datejs是要走的路。現在一切都和諧了。說實話,我不知道datejs是要求。感謝您的回答。 –

0

FIDDLE

var selectedDate='2012-05-14T00:00:00'; 
var formatttedDate=new Date(selectedDate.substr(0,selectedDate.indexOf('T'))); 

document.write(formatttedDate.getFullYear()+'/'+(formatttedDate.getMonth()<10?'0'+formatttedDate.getMonth():formatttedDate.getMonth())+'/'+formatttedDate.getDay()); 
+0

這會丟棄時間部分。爲什麼重新發明輪子? – nalply

1

更新:

第一次作爲一個建議,我想引用date.js.繼

selected.JsInspectionDate = Date.parse(selected.InspectionDate); 

這似乎是工作,但後來我發現這是不夠的,因爲JSON日期字符串可以有一個2012-05-14T00:00:00.0539格式date.js也不能處理。

所以我的解決辦法是

function dateParse(str) { 
    var arr = str.split('.'); 
    return Date.parse(arr[0]); 
} 
... 
selected.JsInspectionDate = dateParse(selected.InspectionDate); 
相關問題