3 回答
TA贡献1803条经验 获得超6个赞
您似乎假设在setDate
不更改原始日期的情况下创建了一个新日期。它不是。相反,它只是修改日期对象并返回一个自引用。
的用法是这样的:
date.setDate(10); date.setMinutes(10);
可以更优雅地写成:
date.setDate(10).setMinutes(10);
如果要创建两个独立的日期,则必须复制日期:
const copy = new Date(oldDate);
TA贡献1772条经验 获得超5个赞
请注意setDate会修改您的引用,而不会创建新引用。
let timeNow = new Date();
let timeShowToday = new Date( //set at 8:00pm everyday
timeNow.getFullYear(),
timeNow.getMonth(),
timeNow.getDate(),
20,
0
);
let timeShowYesterday = new Date(timeShowToday);
timeShowYesterday.setDate(timeShowYesterday.getDate() - 1);
console.log('Yesterday', timeShowYesterday);
console.log('Today', timeShowToday);
let timeDiff = timeShowToday.getTime() - timeNow.getTime();
if (timeDiff < 0) { //recalculate if current Time is past specific time(8:00pm)
const timeShowYesterday = new Date(
timeNow.getFullYear(),
timeNow.getMonth(),
timeNow.getDate(),
20,
0
);
timeShowToday = new Date(timeShowYesterday);
timeShowToday.setDate(timeShowToday.getDate() + 1);
console.log('Yesterday', timeShowYesterday);
console.log('Today', timeShowToday);
}
我更新了
let timeShowYesterday = new Date(timeShowToday);
timeShowYesterday.setDate(timeShowYesterday.getDate() - 1);
和
timeShowToday = new Date(timeShowYesterday);
timeShowToday.setDate(timeShowToday.getDate() + 1);
为避免覆盖您的参考,只需创建一个新日期并进行更新即可。
TA贡献1802条经验 获得超5个赞
发现了问题!
我以为setDate
timeShowToday = timeShowYesterday.setDate( timeShowYesterday.getDate() + 1 );
会从timeShowYesterday创建一个新实例,而不影响它,并将其分配给timeShowToday,但实际上对其进行了修改。
所以+1是问题所在。
添加回答
举报