Javascript New Date() / UTC - GMT cross browser

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

The issue: Different formats for new Date() in IE 10 - IE 11. Javascript:

IE 11 / Chrome :

var m = new Date("2014-07-04T04:00:00");  console.log(m); // Fri Jul 04 2014 06:00:00 GMT+0200 (W. Europe Summer Time)  

IE 10:

var m = new Date("2014-07-04T04:00:00");  console.log(m); // Fri Jul 4 04:00:00 UTC+0200 2014  

Is possible to use one ring to rule them all?

回答1:

You shouldn't pass a string to new Date, specifically for this reason.

Instead, you should either give it the individual arguments:

new Date(2014, 6, 4, 4, 0, 0); // remember months are zero-based 

Or, if you want to give it a time in UTC, try:

var d = new Date(); d.setUTCFullYear(2014); d.setUTCMonth(6); d.setUTCDate(4); d.setUTCHours(4); d.setUTCMinutes(0); d.setUTCSeconds(0); d.setUTCMilliseconds(0); 

You can, of course, make a function to do this.

Alternatively, if you have a timestamp, you can simply do:

var d = new Date(); d.setTime(1404446400000); 


回答2:

To complete the answer a bit. The UTC example given is dangerous, given that you execute on 31st of May (or any other 31st day of month) the following:

var d = new Date(); d.setUTCFullYear(2014); d.setUTCMonth(5); d.setUTCDate(4); d.setUTCHours(4); d.setUTCMinutes(0); d.setUTCSeconds(0); d.setUTCMilliseconds(0); 

it will produce "2014 July 4 04:00:00".

So prefer Date.UTC function instead:

new Date(Date.UTC(2014, 5, 4, 4, 0, 0, 0)) 

it will produce "2014 June 4 04:00:00".



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