Firefox new Date() from string constructs time in local time zone

回眸只為那壹抹淺笑 提交于 2019-12-18 21:53:44

问题


I am trying to create a date object from a string. I get date in ISO format except milliseconds part like "2012-01-30T16:23:12"

Results differ when I run following code in IE, Chrome and Firefox (Link to Fiddle)

currentDate = "2012-01-30T16:23:12";
var date = new Date(currentDate);
alert(date);

IE and Chrome considers the string as UTC but firefox considers in local time zone.

Is there any generic way to get around it except for checking user agent everywhere?


回答1:


You could try appending the zero timezone offset +00:00 for UTC:

currentDate = "2012-01-30T16:23:12+00:00";

Does that help? (Sorry I can't test it without actually changing my timezone.)




回答2:


Hm, possible workaround is to parse string and use methods.

setUTCDate()    
setUTCFullYear()
setUTCHours()

Probably, there is better solution




回答3:


There is no guarantee that the input will be correctly parsed if in the present format. The Date.parse() routine is only required to parse strings in a particular format—parsing other formats is implementation-dependent. If you dare to rely on implementations satisfying the requirement, add data to conform to the specific format:

new Date(currentDate + '.000Z')

Alternatively, use a library that can parse data in the current format, e.g. jQuery or Globalize.js.

Similar considerations apply to writing dates. There is no guarantee of the output format if you use Date.toString(), either explicitly or as in alert(date). Even within a single computer, different browsers will use different localized formats.



来源:https://stackoverflow.com/questions/9062863/firefox-new-date-from-string-constructs-time-in-local-time-zone

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