Parsing ISO8601-like date in JavaScript: new Date() doesn't work across browsers

ぐ巨炮叔叔 提交于 2019-12-13 05:37:45

问题


How do I convert a date string coming from a database into a new Date() object?

If I do the following:

var x = new Date('2013-11-05 11:01:46:0');
alert(x);

It works in Chrome, but in Safari it gives me the string "Invalid Date". Here's the fiddle.


回答1:


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

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.



来源:https://stackoverflow.com/questions/19797608/parsing-iso8601-like-date-in-javascript-new-date-doesnt-work-across-browsers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!