Javascript getTime() returns 与时间对象本身不同的时间
Javascript getTime() returns different time than time object itself
Javascript getTime() returns 与时间对象本身不同的时间。
function doTime(){
var data = [];
var newDate = new Date('2020-01-01');
for (var i = 0; i < 10; i++) {
newDate.setTime(newDate.getTime() + (1000 * 60 * 60));
console.log(newDate); //<<----these times are not the same for some reason, why?
data.push({'date': newDate}); //<<----these times are not the same for some reason, why?
}
console.log(data);
}
和输出!!
Wed Jan 01 2020 03:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 04:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 05:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 06:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 07:00:00 GMT+0200 (Eastern European Standard Time)
................
(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
1: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
2: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
3: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
4: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
................
顺便说一句,我已经用稍微不同的代码解决了这个问题,但是有人可以解释为什么会这样吗?
您没有在循环中创建新的引用,因此您每次都在改变相同的 newDate
。您还调用了 console.log
,因此此时它已转换为其控制台格式。
Javascript getTime() returns 与时间对象本身不同的时间。
function doTime(){
var data = [];
var newDate = new Date('2020-01-01');
for (var i = 0; i < 10; i++) {
newDate.setTime(newDate.getTime() + (1000 * 60 * 60));
console.log(newDate); //<<----these times are not the same for some reason, why?
data.push({'date': newDate}); //<<----these times are not the same for some reason, why?
}
console.log(data);
}
和输出!!
Wed Jan 01 2020 03:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 04:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 05:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 06:00:00 GMT+0200 (Eastern European Standard Time)
Wed Jan 01 2020 07:00:00 GMT+0200 (Eastern European Standard Time)
................
(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
1: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
2: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
3: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
4: {date: Wed Jan 01 2020 12:00:00 GMT+0200 (Eastern European Standard Time)}
................
顺便说一句,我已经用稍微不同的代码解决了这个问题,但是有人可以解释为什么会这样吗?
您没有在循环中创建新的引用,因此您每次都在改变相同的 newDate
。您还调用了 console.log
,因此此时它已转换为其控制台格式。