Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript New Date() / UTC - GMT cross browser

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?

like image 808
Mario Levrero Avatar asked Jul 01 '14 14:07

Mario Levrero


People also ask

Does new Date return UTC JavaScript?

It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

How can I get the current Date and time in UTC or GMT in JavaScript?

var now = new Date(); var utc = new Date(now. getTime() + now. getTimezoneOffset() * 60000);

What does new Date () return in JavaScript?

Return value Calling the Date() function (without the new keyword) returns a string representation of the current date and time, exactly as new Date().toString() does.

How do you convert Date to UTC?

The Javascript date can be converted to UTC by using functions present in Javascript Date object. The toUTCString() method is used to convert a Date object into a string, according to universal time. The toGMTString() returns a string which represents the Date based on the GMT (UT) time zone.


2 Answers

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);
like image 53
Niet the Dark Absol Avatar answered Oct 05 '22 23:10

Niet the Dark Absol


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".

like image 25
Bohdan Tsymbala Avatar answered Oct 06 '22 00:10

Bohdan Tsymbala