[英]how to get selected week days dates between Start date and end date with 14 day recurrence pattern using Pure JavaScript
我需要返回一些日期 object,它發生在開始日期和結束日期之間,具有重復模式,並使用純 javaScript(無 postman 或時刻)給出工作日。 我能夠獲得 1 周的日期 object。 但我無法獲得日期 object 超過一周(14 或 21 天)。 這是我的以下代碼。
function dates{
var startDate = new Date("2020/06/22");
var endDate = new Date("2020/08/16");
var recurrencePattern = 14 ;// 2 weeks
var daysSelected = [0,1]; //0 - sunday , 1 - monday
var datesObj = [];
while(startDate <= endDate){
var i=0;
while(i<daysSelected.length){
if(startDate.getDay() == daysSelected[i]){
datesObj.push(startDate.getFullYear()+"-"+(startDate.getMonth()+01)+"-"+startDate.getDate());
}
i++;
}
startDate.setDate(startDate.getDate() +1);
}
return datesObj;
}
我應該得到的 output(每 2 周,在 2020 年 6 月 22 日和 2020 年 8 月 16 日之間選擇的周日和周一)是
datesObj["22-06-2020","5-07-2020","6-07-2020","19-07-2020","20-07-2020","2-08-2020","3-08-2020","16-08-2020"]
但我讓所有星期日和星期一的日期都從開始日期和結束日期開始。 任何人都可以解決這個問題。
您可以使用以下代碼更新您的while(i<daysSelected.length){... }
代碼。
if (daysSelected.includes(startDate.getDay())) {
datesObj.push(startDate.getFullYear() + "-" + (startDate.getMonth() + 01) + "-" + startDate.getDate());
}
此外,當您遇到last day of week
即startDate.getDay() == 6
時,要跳過recurrencePattern = 14
天,然后跳過recurrencePattern-7+1
天。 您需要從recurrencePattern
中減去7
,因為您已經使用loop
處理了one week
。 還使用datesObj.length > 0
因此它只會跳過actually
為相應weeks
添加dates
的周。
下面是完整的代碼。 你可以檢查一下。
function dates(startDate, endDate) { var recurrencePattern = 14; // 2 weeks var daysSelected = [0, 1]; //0 - sunday, 1 - monday var datesObj = []; while (startDate <= endDate) { if (daysSelected.includes(startDate.getDay())) { datesObj.push(startDate.getFullYear() + "-" + (startDate.getMonth() + 01) + "-" + startDate.getDate()); } if (datesObj.length > 0 && startDate.getDay() == 6) { startDate.setDate(startDate.getDate() + (recurrencePattern - 7 + 1)); } else { startDate.setDate(startDate.getDate() + 1); } } return datesObj; } console.log(dates(new Date("2020/06/22"), new Date("2020/08/16")));
更新var daysSelected = [0, 4];
包括0
到4
之間的所有天數。
function dates(startDate, endDate) { var recurrencePattern = 14; // 2 weeks var daysSelected = [0, 4]; //0 - sunday to 4 - thursday var startDay = Math.min(...daysSelected); var endDay = Math.max(...daysSelected); var datesObj = []; while (startDate <= endDate) { if (startDay <= startDate.getDay() && endDay >= startDate.getDay()) { datesObj.push(startDate.getFullYear() + "-" + (startDate.getMonth() + 01) + "-" + startDate.getDate()); } if (datesObj.length > 0 && startDate.getDay() == 6) { startDate.setDate(startDate.getDate() + (recurrencePattern - 7 + 1)); } else { startDate.setDate(startDate.getDate() + 1); } } return datesObj; } console.log(dates(new Date("2020/06/22"), new Date("2020/08/16")));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.