【问题标题】:Why doesn't this new Date work in javascript?为什么这个新日期在 javascript 中不起作用?
【发布时间】:2013-03-12 19:34:02
【问题描述】:

我正在尝试显示格式为“MMM.dd HH:mm:ss.nnn”的日期。它在 IE 中错误地呈现它,我已经花了很长时间,但我无法弄清楚为什么我不能让它工作。

我知道 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();

会起作用的。

例子:

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,然后将其转换为字符串,就像第一个片段中的代码一样。我做错了什么?

谢谢。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

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

【讨论】:

  • 所以我很尴尬,但事实证明有一个 datejs 在后台做了很多魔法
猜你喜欢
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 2012-02-22
  • 2016-12-22
  • 1970-01-01
相关资源
最近更新 更多