8

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?

Mario Levrero
  • 3,345
  • 4
  • 26
  • 57
  • 4
    Yes, use **moment.js**: http://momentjs.com/ – Ian Jul 01 '14 at 14:36
  • 2
    For consistent behavior, include a timezone within the string. The issue is a difference in opinion among browser vendors as to which timezone should be assumed when it's absent [from a string of this format](http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15). – Jonathan Lonowski Jul 01 '14 at 14:40

2 Answers2

7

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);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

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

  • Why dangerouse? I got `"2014-06-04T04:00:00.000Z"` in Google Chrome – rofrol Jan 11 '21 at 20:46
  • 1
    As explained - "given that you execute on 31st of May (or any other 31st day of month)" The created date will have 31 as day of month and when you switch to month 5 which doesn't have 31st day it will bump the month number by one and make day 1. So effectively you've set the wrong month. If you change the order of operations to first set the day and then month you'll step into the same situation. That's why JS Date() plus imperative operations on it is a dangerous practice. – Bohdan Tsymbala Mar 06 '21 at 12:48