'How to make a for loop to gather every day of a week that is between months?
So, i need to gather all days the current week, from Sunday to Saturday, i started making a code that takes the actual date and make a for loop to push each day into a array, the problem is that on weeks like this one (that begins in one month and finish in another) the code wont work.
Here is the code:
const createWeek = async() => {
const d = new Date();
let month = d.getMonth() + 1;
let year = d.getFullYear();
const inicialDate = d.getDate() - d.getDay();
const lastDate = inicialDate + 6;
console.log(d, 'current date')
let firstDay = new Date(d.setDate(inicialDate));
let lastDay = new Date(d.setDate(lastDate))
let week = []
for (let i = firstDay.getDate(); i <= lastDay.getDate(); i++) {
week.push(`${i.toLocaleString().length <= 1 ? "0" + i : i}${month.toLocaleString().length <= 1 ? "0" + month : month}${year}`);
}
return week;
}
So i know that the problem is because in my for loop the first day of the week is bigger than the final day of the week, but i dont know how to deal with that. I want to know what is the best aproach to this.
Thanks for your help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|