我正在计算当前和前6天的日期。这应该只需从上一个日期减去1就可以了,所以我实现了我目前的解决方案,如下所示:
let currentDay = new Date();
let nextDay = new Date();
for (let i = 0; i < 7; i++) {
nextDay.setDate(currentDay.getDate() - i);
console.log("i=" + i + "->" + nextDay);
}
然而,这是输出:
i = 0 -> Thu Dec 03 2020 10: 20: 51 GMT + 0100(Central European Standard Time) //today
i = 1 -> Wed Dec 02 2020 10: 20: 51 GMT + 0100(Central European Standard Time) //yesterday
i = 2 -> Tue Dec 01 2020 10: 20: 51 GMT + 0100(Central European Standard Time) //day before yesterday
i = 3 -> Mon Nov 30 2020 10: 20: 51 GMT + 0100(Central European Standard Time) //3 days ago
i = 4 -> Fri Oct 30 2020 10: 20: 51 GMT + 0100(Central European Standard Time) //skips an entire month
i = 5 -> Mon Sep 28 2020 10: 20: 51 GMT + 0200(Central European Summer Time) //skips another month, 2 days and switches to summertime
i = 6 -> Fri Aug 28 2020 10: 20: 51 GMT + 0200(Central European Summer Time) //skips another month
它在上个月底运行时如预期一样工作(本月没有逃脱(。它在进入11月时失败了。我似乎找不到原因。
您永远不会从第一天开始重新创建nextDate
。看看这个:
function addDays(a_oDate: Date, days: number): Date {
a_oDate.setDate(a_oDate.getDate() + days);
return a_oDate;
}
function printLast7Days(a_oDate: Date): void {
for (let i = 0; i < 7; i++) {
let nextDay = new Date(a_oDate); // recreate date from the initial date
addDays(nextDay, -i); // effectively subtracts i days
console.log("i=" + i + "->" + nextDay.toDateString());
}
}
printLast7Days(new Date());
游乐场