2012-08-22 47 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); 
相关问题