【问题标题】:Javascript Date from string giving different output from Chrome to Firefox字符串中的 Javascript 日期,提供从 Chrome 到 Firefox 的不同输出
【发布时间】:2013-05-14 08:31:47
【问题描述】:

我正在尝试编写一些 javascript 代码来格式化我想要的日期,但我无法让它在 Firefox 上运行(它在 Chrome 上按我想要的方式运行)。

我在表单中的输入是 05/01/13 (mm/dd/yy),我想要 2013-05-01 (yyyy/mm/dd)。

为此,我所做的是这样的:

var formDate = document.getElementById("start").value;
var myDate = new Date(formDate);
var startDate = new Date();

startDate.setMonth(myDate.getMonth() + 1);
startDate.setFullYear(myDate.getFullYear());
var FormattedDate = startDate.getFullYear() + "-" + ((startDate.getMonth() <= 10) ? "0" : "") + startDate.getMonth() + "-01"; // the day is always 01

alert(FormattedDate);

您可以在这两种浏览器上试用:http://jsfiddle.net/j4BLH/

在 Google Chrome 上,此代码为我提供了例如 5 月的 2013-05-01,但在 Firefox 上,我有 1913-05-01

我知道我可以写像 "20" + startDate.getYear() 这样的东西,但我想知道为什么结果从 Chrome 到 Firefox 不同?如果你有更好的方法来编写我粘贴在这里的代码,请告诉我:)

谢谢!

【问题讨论】:

标签: javascript google-chrome firefox date


【解决方案1】:

来自spec

但是,表达式 Date.parse(x.toLocaleString()) 不是必需的 产生与前面三个表达式相同的数值 而且,一般来说, Date.parse 产生的值是 当给定任何不存在的 String 值时,实现依赖于 符合日期时间字符串格式 (15.9.1.15) 并且不能 由 toString 或 toUTCString 在该实现中生成 方法。

通过将日期字符串传递给构造函数来创建日期对象时,解析的方法与Date.parse完全相同。

您使用 2 位数年份的日期格式不符合标准。因此,这些日期的解析方式似乎是特定于实现的,这意味着它取决于所使用的 Javascript 引擎。在 Google 的情况下,它通常是 V8,而在 Firefox 中,我相信是 TraceMonkey 或 Rhino。

简而言之,你真的应该使用 4 位数的年份,因为 JS 标准中没有 YY。

【讨论】:

  • 感谢您的回答,这很好地总结了 cmets 中所说的内容!
猜你喜欢
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 2015-10-06
  • 1970-01-01
相关资源
最近更新 更多