无法从包含milisec的日期创建新的Date()对象' 2015-05-14 08:08:48.792'

时间:2015-12-16 09:41:02

标签: javascript datetime firefox

   var newDate= new Date('2015-05-14 08:08:48.792');
   console.log(newDate);

如果我运行上面的代码,我会得到以下内容:Date {Invalid Date}。 我在firefox中有这个问题,在chrome中它可以工作。

enter image description here

我需要创建这个对象,因为我需要在两个包含毫秒的日期之间做区别。 例如' 2015-05-14 08:08:48.792' - ' 2015-05-14 08:08:50.792'

2 个答案:

答案 0 :(得分:2)

在处理日期字符串时,您应该使用可识别的格式。

如果查看Date构造函数的Mozilla文档,则dateString重载接受一个字符串,该字符串表示日期格式,因为它对Date.parse()有效。

日期: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

Date.Parse: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

我建议使用 ISO8601 ,因为它通常更受支持; '2015-05-14T08:08:48.792Z'。注意T表示模式的时间段的开始,并且最好是结尾Z,表示这是UTC时间。

var newDate = new Date('2015-05-14T08:08:48.792Z');
document.write(newDate);

更新了小提琴:https://jsfiddle.net/7tkmjszv/1/

希望这有帮助! :)

答案 1 :(得分:0)

不确定您是否可以将该日期字符串格式用于JS中的新日期。 尝试解析和

var newDate = new Date('2015', '05', '14', '08', '08', '48', '792');