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?
Date() creates a Local date. new Date() creates a UTC date.
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.
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With