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?
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');
链接地址: http://www.djcxy.com/p/3076.html
上一篇: 默认值为今天?