NodeJS日期加月份创建无限循环



我正试图在firebase中创建一个云函数,在未来的一年里,它每天、每周、每月或每年都会做一些事情。不知怎么的,日期循环不起作用。有人知道为什么会这样吗?我的代码:

//Format date to yyyy-mm-dd
const splitDate = date.split('-');
const year = splitDate[2];
const month = splitDate[1];
const day = splitDate[0];
const nextYear = [parseInt(year) + 1, parseInt(month)  - 1, parseInt(day)];
let curDate = new Date(year, parseInt(month) - 1, day);
while(true){
//increase the date of the appointment by the specified amount of time each iteration
if (recurring === 'daily') {
curDate.setDate(curDate.getDate() + 1);
} else if (recurring === 'weekly') {
curDate.setDate(curDate.getDate() + 7);
} else if (recurring === 'monthly') {
curDate.setMonth(curDate.getMonth() + 1);
} else if(recurring === 'yearly') {
curDate.setFullYear(curDate.getFullYear() + 1);
} else{
console.log('recurring value was not entered or invalid, function aborted');
break;
}
console.log(curDate);
//Test if end date is passed. if so, stop function
if (nextYear[0] < curDate.getFullYear()) {
break;
} else if (nextYear[0] == curDate.getFullYear()) {
if (nextYear[1] < curDate.getMonth() + 1) {
break;
} else if (nextYear[1] == curDate.getMonth()) {
if (nextYear[2] < curDate.getDate()) {
break;
}
}
}
//format new data, add a field that indicates this appointment does not need a creation email
//Add the appointment with the new data in the appointments collection
}
return true;
})

这个代码几乎可以工作,但它没有得到正确的日期。当每天测试时,它停止在以下位置。

2021-09-01T00:00:00.000Z 

当每周尝试时,它也会错过一周。我想是因为日期检查不正确。每月和每年做工作,每周和每天在正确的月份结束。有人知道为什么当它在正确的一年中的正确月份出现时,它会立即断裂吗?

我在您的代码中注意到了几个问题:

1-在测试代码时,似乎没有正确计算日期。为了解决这个问题,我用以下方式修改了它:

let curDate = new Date(year, month, day);
while(true){
//increase the date of the appointment by the specified amount of time each iteration
if (recurring === 'daily') {
curDate.setDate(curDate.getDate() + 7);
} else if (recurring === 'weekly') {
curDate.setDate(curDate.getDate() + 7);
} else if (recurring === 'monthly') {
curDate.setMonth(curDate.getMonth() + 7);
} else if(recurring === 'yearly') {
curDate.setFullYear(curDate.getFullYear() + 7);
} else{
console.log('recurring value was not entered or invalid, function aborted');
break;
}
console.log(curDate);
...

请注意,我已经使用单独的日期和时间组件值删除了formatDate,因为将数组传递给new date((会给我一个错误的月份(它的读数是8,而在JS中应该表示9,因为月份从0开始(


2-getYear((方法已弃用,应改用getFullYear(。


3-您应该将循环中最后一个If Else语句中的日期和月份的小于符号更改为大于标志,因此看起来如下:

----------

编辑

进一步研究这个问题,您的上一个If Else语句最初似乎是正确的。恢复小于的标志将为您解决新问题:

if (nextYear[0] < curDate.getFullYear()) {
break;
} else if (nextYear[0] == curDate.getFullYear()) {
if (nextYear[1] < curDate.getMonth()) {
break;
} else if (nextYear[1] == curDate.getMonth()) {
if (nextYear[2] < curDate.getDate()) {
break;
}
}
}

如果有帮助,请告诉我。

最新更新