我正在根据当前时间重新计算时间。 timeShowToday是每天的特定时间(设置为8:00 pm),以显示一些盲目的答案。
_checkTime = () => {
let timeNow = new Date();
let timeShowToday = new Date( //set at 8:00pm everyday
timeNow.getFullYear(),
timeNow.getMonth(),
timeNow.getDate(),
20,
0
);
let timeShowYesterday = timeShowToday.setDate(timeShowToday.getDate() - 1);
let timeDiff = timeShowToday.getTime() - timeNow.getTime();
if (timeDiff < 0) { //recalculate if current Time is past specific time(8:00pm)
let temp = new Date(
timeNow.getFullYear(),
timeNow.getMonth(),
timeNow.getDate(),
20,
0
);
console.log(temp);
timeShowYesterday = temp;
timeShowToday = timeShowYesterday.setDate(
timeShowYesterday.getDate() + 1
);
console.log(timeShowYesterday);
}
这里的问题是,尽管我刚刚将temp分配给timeShowYesterday,但变量temp和timeShowYesterday具有不同的日期时间。这是在我进行控制台日志时得到的日志:
05-03 00:26:59.623 ReactNativeJS:temp:2019年5月3日星期五20:00:00 GMT + 0900
05-03 00:26:59.623 ReactNativeJS:timeShowYesterday:2019年5月4日星期六20:00:00 GMT + 0900
如您所见,temp正确记录了当前时间,但是timeShowYesterday具有+1天。我不知道为什么会这样,因为我所做的只是将temp分配给timeShowYesterday。
我错过了什么吗? 谢谢答案 0 :(得分:2)
请注意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);
为避免覆盖您的推荐,只需创建一个新日期并进行更新即可。
答案 1 :(得分:2)
您似乎假设setDate
创建了一个新日期而不更改原始日期。它不是。相反,它只是修改日期对象并返回一个自引用。
它的用法是这样的:
date.setDate(10);
date.setMinutes(10);
可以更优雅地写为:
date.setDate(10).setMinutes(10);
如果要创建两个独立的日期,则必须copy the date:
const copy = new Date(oldDate);
答案 2 :(得分:0)
发现了问题!
我以为setDate
timeShowToday = timeShowYesterday.setDate(
timeShowYesterday.getDate() + 1
);
将在不影响它的情况下从timeShowYesterday创建一个新实例,并将其分配给timeShowToday,但实际上对其进行了修改。
所以+1是问题所在。