Javascript New Date () / UTC - GMT cross browser

Problem : 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 

Can one ring be used for all of them?

+6
source share
2 answers

You should not pass a string to new Date , especially for this reason.

Instead, you must specify either individual arguments:

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

Or, if you want to give it 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 for this.

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

 var d = new Date(); d.setTime(1404446400000); 
+6
source

To fulfill the answer a bit. The above UTC example is dangerous given that you are doing on May 31 (or any other 31st day of the 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); 

he will produce "2014 July 4th 04:00:00".

So, instead of Date.UTC :

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

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

0
source

Source: https://habr.com/ru/post/971597/


All Articles