Home > database >  How to make a for loop to gather every day of a week that is between months?
How to make a for loop to gather every day of a week that is between months?

Time:03-03

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.

CodePudding user response:

I'd suggest using Date.setDate() to adjust each day, this will adjust the month correctly as well.

We start by getting the weekStart day, by subtracting the result of currentDay.getDay() from currentDate.getDate() and using this as the input to setDate().

We can then use Array.from() to generate our list of seven days.

I'd suggest first creating an array of seven dates, then creating a custom formatting function, e.g. formatDate() for this purpose. This allows us to separate the logic of creating and displaying the dates.

function createWeek(currentDay = new Date()) {
    const weekStart = new Date(currentDay);
    weekStart.setDate(currentDay.getDate() - currentDay.getDay());
    return Array.from( { length: 7 }, (v,k) => { 
        const dt = new Date(weekStart);
        dt.setDate(weekStart.getDate()   k);
        return dt;
    })
}

function formatDate(date) {
    return [date.getDate(), date.getMonth()   1, date.getFullYear()]
     .map(n => (n   '').padStart(2, '0'))
     .join('');
}

const weekDates = createWeek();
console.log('Formatted dates:')
for(let date of weekDates) {
    console.log(formatDate(date));
}
.as-console-wrapper { max-height: 100% !important; }

  • Related