Javascript Date(dateString) 在特定服务器和浏览器上返回 NaN
我使用的是 Javascript Date(string) 构造函数,日期格式为“yyyy-mm-dd”。构造函数在 IE 9 和 Firefox 中工作得很好,除非应用程序在运行 IIS 的测试虚拟机上运行。如果在虚拟机上,在 IE 9 中它会返回“NaN”,但在 Firefox 中仍然可以正常工作。
var dateAsString = "2011-11-09";
var dateCreated = new Date(dateAsString);
我假设服务器与客户端 Javascript 无关。有什么建议吗?
I'm using the Javascript Date(string) constructor with a date format of "yyyy-mm-dd". The constructor works just fine in IE 9 and Firefox unless the app is running on our testing VM which is running IIS. If it's on the VM, in IE 9 it returns 'NaN', but still works normally in Firefox.
var dateAsString = "2011-11-09";
var dateCreated = new Date(dateAsString);
I was under the assumption that the server had nothing to do with client-side Javascript. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于我们这些想知道如何用斜杠替换连字符(又名破折号)的人来说:
这使用了这个函数:
在我的例子中,有选择地将连字符转换为斜杠要容易得多(仅在需要的情况下) Date() 函数)而不是替换代码中各处的日期格式。
注意:您确实需要定义一个单独的“响应”变量并将替换操作结果的值分配给它。如果不这样做,该字符串将在 Chrome 中原样返回。这并不是一个大问题,因为 Chrome 本来就没有连字符日期字符串的问题。但仍然...
And for those of us who want to know how to replace hyphens (aka dashes) with slashes:
That uses this function:
In my case it's much easier to convert hyphens to slashes selectively (only where it's needed for the Date() function) than to replace the date format everywhere in my code.
Note: you really need to define a separate 'response' variable and assign it the value of the replace operation result. If you don't, the string is returned unaltered in Chrome. That's not a huge problem, since Chrome doesn't have a problem with hyphenated date strings to begin with. But still...
如果可以的话,只需使用斜杠而不是连字符。
编辑:扩展说明...
ISO 8601 标准格式使用连字符作为日期分隔符。我的回答并不意味着您不需要遵循标准。如有必要,您可以仅对 Date 构造函数使用斜杠。
Just use slashes instead of hyphens if you can.
EDIT: Expanded clarification...
The ISO 8601 standard format uses the hyphen as a date separator. My answer does not mean you do not need to follow standards. You can use slashes only for the Date constructor if necessary.
这是因为日期格式的问题。由于某些原因,IE 和 Safari 会出现
yyyy-mm-dd
错误。使用另一种日期格式,您应该已准备就绪。这里讨论的是:
http://biostall.com /javascript-new-date-returning-nan-in-ie-or-invalid-date-in-safari
It's because of the date format. For some reason, IE and Safari get tripped up with
yyyy-mm-dd
. Use another date format and you should be all set.It's talked about here:
http://biostall.com/javascript-new-date-returning-nan-in-ie-or-invalid-date-in-safari
我建议尝试一种更可靠的日期解析形式。下面的示例使用
setFullYear()
。 IE 使用下面的代码会产生不同的结果吗?来源:http://jibbering.com/faq/#parseDate
I suggest attempting a more reliable form of date parsing. The example below uses
setFullYear()
. Does IE produce a different result with the code below?Source: http://jibbering.com/faq/#parseDate