Reputation: 389
I am working on something in which I should be able to choose the date with having a 3 days gap from current date. Also, the weekend should be excluded from the 3 days of gap. I was able to do the first task and lost with the logic to proceed the second. I am aware of using date.getDay() but I am lost for building up the algorithm. Please explain where should I construct.
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);
Upvotes: 1
Views: 60
Reputation: 4011
Here's how I would go about it.
I explained my reasoning as comments in the code
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}`);
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const minDate = `${year}-${month}-${day}`; // Converting the date to a the YYYY-MM-DD format.
console.log(minDate);
Upvotes: 1