2013-03-12 97 views
1

我试图显示格式为“MMM。dd HH:mm:ss.nnn”的日期。它在IE中渲染不正确,我花了相当长的时间,我无法弄清楚为什么我不能让它工作。为什么这个新日期不能在JavaScript中工作?

我知道Date.UTC返回Date对象中的毫秒数自1月1日,1970年因此,

var newDate = new Date(Date.UTC(year, month[, date[, hrs[, min[, sec[, ms]]]]]) 
newDate.toString("MMM. dd HH:mm:ss.")+row.timestamp.getMilliseconds(); 

会工作。

例子:

var newDate = new Date(Date.UTC(1950, 10, 10, 10, 09, 09, 100)); 
row.timestamp_f = newDate.toString("MMM. dd HH:mm:ss."); // Output => Nov. 10 05:09:09. 

但是,我从一个jquey.each功能这个作用中,使我一起工作的日期的字符串是ISO 8601: “2013-03-12T15:14:10.483” 。所以,这是我的想法。

var numMilisecond = Date.parse(row.timestamp); 
var newDate = new Date(numMilisecond); 
row.timestamp_f = newDate.toString("MMM. dd HH:mm:ss."); // Output => Dec. 31 19:00:00. 

row.timestamp是从JSON响应

{"timestamp":"2013-03-12T15:14:10.483" ...} 

为什么没有代码工作? Date.parse应返回自1970年1月1日以来的毫秒数,然后创建一个新的Date obj,然后将其转换为字符串,就像第一个snipet中的代码一样。我究竟做错了什么?

谢谢。

+0

[请更正您的代码以使用代码块而不是blockquotes](http://stackoverflow.com/editing-help)。 – zzzzBov 2013-03-12 19:36:36

+4

IE正在使用[非标准'toString'行为](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toString) – Blazemonger 2013-03-12 19:36:53

+1

可能的重复[在JavaScript中格式化日期](http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript) – Blazemonger 2013-03-12 19:37:27

回答

0

Date.toString shouldn't accept any arguments。如果你想要一个真正的日期格式解决方案,你需要使用plugin或者自己推出。

var shortmonths = ['Jan','Feb','Mar','Apr',]; // remaining months are left as an exercise for the reader 
row.timestamp_f = shortmonths[newDate.getMonth()] 
        + ". "+newDate.getDate() + " " 
        + newDate.toLocaleTimeString() + "."; 
+0

所以我很尴尬,但事实证明有一个datejs在背景中做了很多魔术 – okysabeni 2013-03-13 16:50:24

相关问题