在JavaScript中解析ISO8601类似的日期:new Date()不能跨浏览器工作 [英] Parsing ISO8601-like date in JavaScript: new Date() doesn't work across browsers
问题描述
如何将日期字符串从数据库转换为新的Date()对象?
How do I convert a date string coming from a database into a new Date() object?
如果我执行以下操作:
var x = new Date('2013-11-05 11:01:46:0');
alert(x);
它适用于Chrome,但在Safari中,它给我的字符串无效的日期。
这里是小提琴。
It works in Chrome, but in Safari it gives me the string "Invalid Date". Here's the fiddle.
推荐答案
new Date(string)
接受的字符串的格式取决于实现。如果浏览器正确地实现了ES5规范,则严格的子集的法定ISO 8601字符串。基本上,您需要使用UTC而不是本地时间,在日期和时间之间放置一个T,而不是一个空格,在整数和小数秒之间使用小数点,而不是冒号,并在末尾附加Z
The format of strings accepted by new Date(string)
is implementation-dependent. If the browser correctly implements the ES5 specification, however, a strict subset of legal ISO 8601 strings should be accepted. Basically, you need to use UTC instead of local time, put a "T" instead of a space between the date and time, use a decimal point instead of a colon between integral and fractional seconds, and append a "Z" on the end of the whole thing:
2013-11-05T11:01:46.000Z
也许你可以让你的数据库输出格式的日期;否则,您应该查看第三方库,例如 moment.js 。
Perhaps you can get your database to output the dates in that format; otherwise, you should look into a third-party library, such as moment.js.
这篇关于在JavaScript中解析ISO8601类似的日期:new Date()不能跨浏览器工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!