0

I would like to have an array with dates of this current week and the next week. I tried to implement this with a for loop and a while loop but didn't succeed at the moment

getTwoWeeks = () => {

    let twoWeeks = [];
    let days = 14;
    let today = new Date;
    let calcFirst = today.getDate() - today.getDay();
    let firstDayOfWeek = new Date(today.setDate(calcFirst));

    for(let i=0; i<days; i++) {
        twoWeeks.push( new Date(today.setDate(firstDayOfWeek + days[i])) )
    }

    console.log('twoWeeks===',twoWeeks )
}
norbitrial
  • 14,716
  • 7
  • 32
  • 59
Raz
  • 189
  • 1
  • 12

3 Answers3

2

You can calculate first the Monday of the current week then iterate from there till 14 days.

const today = new Date();
const dayOfWeek = today.getDay();
const lastMonday = new Date(today.setDate(today.getDate() + (dayOfWeek * -1 + 1)));

for (let i = 1, d = lastMonday; i <= 14; i++, d.setDate(d.getDate() + 1)) {
  console.log(new Date(d));
}
norbitrial
  • 14,716
  • 7
  • 32
  • 59
1

You can do this as follows:

getTwoWeeks = () => {
               let twoWeeks = [];
               let days = 14;
               let today = new Date();
               twoWeeks.push(today)
               for(let i = 0; i < days-1; i++) {
                    var next = new Date();
                    next.setDate(today.getDate()+1);
                    twoWeeks.push(next);
                    today = next;
               }
               console.log('twoWeeks===',twoWeeks )
}
getTwoWeeks();
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
0

it looks like your are misusing your index "i" in the for loop. "days" is not an array, it is an integer. Try the following:

let twoWeeks = [];
let days = 14;
let today = new Date;
let calcDate = new Date(today.setDate(today.getDate() - today.getDay()));

for(let i=0; i<days; i++) {
  calcDate.setDate(calcDate.getDate() + 1)
  twoWeeks.push(new Date(calcDate))
}

console.log(twoWeeks)

Hope this helps!

Branden Keck
  • 462
  • 3
  • 12