我正在工作的东西,我应该能够选择日期与有3天的差距,从当前的日期。还有,周末应该排除在3天的空档之外。我能够完成第一项任务,却失去了继续第二项任务的逻辑。我知道使用date.getDay(),但我对构建算法感到迷茫。请解释一下我应该在哪里施工。
const addDate = 7;
const min = new Date(Date.now() + (addDate * (24 * 60 * 60 * 1000)));
const year = min.getFullYear();
const month = (min.getMonth() + 1).toString().padStart(2, '0');
const day = min.getDate().toString().padStart(2, '0');
//const weekend = min.getDay();
//console.log("weekend is "+weekend);
const minDate = `${year}-${month}-${day}`;
document.getElementById("dateAve").setAttribute("min", minDate);
我会这样做。
我在代码中以注释的形式解释了我的推理
null
let datesAdded = 0; // For keeping track of the number of times we've changed the date
const maxDatesToAdd = 3; // Number of extra days you want to add to today
const weekends = [0, 6]; // indices of weekends you get from Date.getDay();
let date = new Date();
console.log(`Today: ${date}`);
while (datesAdded < maxDatesToAdd) {
const newDate = new Date(date.getTime() + (24 * 60 * 60 * 1000));
date = newDate; // Changing the date to newDate
if (weekends.includes(newDate.getDay())) continue; // Checking if the day we've added is a weekend
datesAdded++; // Incrementing if the day isnt a weekday and for the while loop to eventually break
}
console.log(`3 days from today without weekends: ${date}`);