Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date constructors provide unexpected results when called with similar arguments

I got one weird issue with Date object initialization. And wondering if someone can explain why..

var exp1 = new Date('2014-10-17');
var exp2 = new Date(2014,9,17);
var exp3 = new Date('17 Oct 2014');
console.log(exp1);
console.log(exp2);
console.log(exp3);

Results:

 Thu Oct 16 2014 18:00:00 GMT-0600 (MDT) // 16th?
 Fri Oct 17 2014 00:00:00 GMT-0700 (MST) // Why GMT -7
 Fri Oct 17 2014 00:00:00 GMT-0600 (MDT) // The only one that works as expected

Why are these three Date objects so different?

like image 661
badaboom Avatar asked Oct 16 '14 22:10

badaboom


People also ask

What is the difference between new Date () and Date?

Date() creates a Local date. new Date() creates a UTC date.

What does new Date () return?

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 many arguments does a default constructor have?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.

What does a constructor do?

A constructor is a special method of a class or structure in object-oriented programming that initializes a newly created object of that type. Whenever an object is created, the constructor is called automatically.


1 Answers

The first date is treated as GMT since no time zone offset is provided. When logged out it shows the time in your local timezone. Adding an offset (exp4 below), I get the date expected.

var exp1 = new Date('2014-10-17');
var exp2 = new Date(2014,9,17);
var exp3 = new Date('17 Oct 2014');
var exp4 = new Date('2014-10-17z-0500');

Results:

Thu Oct 16 2014 19:00:00 GMT-0500 (Central Daylight Time)
Fri Oct 17 2014 00:00:00 GMT-0500 (Central Daylight Time) 
Fri Oct 17 2014 00:00:00 GMT-0500 (Central Daylight Time) 
Fri Oct 17 2014 00:00:00 GMT-0500 (Central Daylight Time) 

I am not sure about exp2 for you, but suspect it has something to do with daylight savings time and that you live in an area that does not observe daylight savings (Arizona?).

Edit: this seems to be browser specific. The results above were generated in Chrome while in IE 11, exp4 was an invalid date. For IE 11 I had to use this format:

var exp4 = new Date('2014-10-17T00:00-05:00');
like image 50
Jeff Ogata Avatar answered Oct 05 '22 13:10

Jeff Ogata