简体   繁体   English

为什么这个新的Date在javascript中不起作用?

[英]Why doesn't this new Date work in javascript?

I'm trying to display a date with format "MMM. dd HH:mm:ss.nnn". 我正在尝试以“ MMM。dd HH:mm:ss.nnn”格式显示日期。 It is rendering it incorrectly in IE and I have spent quite some time and I can't figure out why I can't get this to work. 它在IE中错误地渲染了它,我花了很多时间,而且我不知道为什么我无法使它正常工作。

I know that Date.UTC returns the number of miliseconds in a Date object since Jan 1, 1970. So, 我知道Date.UTC返回自1970年1月1日以来Date对象中的毫秒数。

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

will work. 将工作。

Example: 例:

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.

But, I am interating this from a jquey.each function so the date string that I am working with is an ISO 8601: "2013-03-12T15:14:10.483". 但是,我正在从jquey.each函数进行插入,因此我正在使用的日期字符串是ISO 8601:“ 2013-03-12T15:14:10.483”。 So, this is what I have in mind. 所以,这就是我的想法。

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 is from a JSON response row.timestamp来自JSON响应

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

Why doesn't the code work? 为什么代码不起作用? Date.parse should return the number of miliseconds since Jan 1, 1970 and then I create a new Date obj and then convert it to string just like the code in the first snipet. Date.parse应该返回自1970年1月1日以来的毫秒数,然后创建一个新的Date obj,然后将其转换为字符串,就像第一个片段中的代码一样。 What am I doing wrong? 我究竟做错了什么?

Thanks. 谢谢。

Date.toString shouldn't accept any arguments . Date.toString不应接受任何参数 If you want a true date-formatting solution, you'll need to use a plugin or roll your own. 如果您想要一个真正的日期格式解决方案,则需要使用一个插件或自己动手制作。

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() + ".";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM