chovy
chovy

Reputation: 75686

How do I get an array of all days in the week given the current date in javascript?

I have the weekday value (0-6 for Sun-Sat)...how do I get an array of days (starting on Sunday for the given week?

Here is what I'm trying to do:

A user clicks a day (ie: May 10) and it generates an array of the dates for the current week:


    function selectWeek(date) {
        selectedWeek = [];

        let d = new Date(date.key);

        console.log(d);
        console.log(date.weekday, 'weekday');

        console.log(date);
        for (let i = 0; i < date.weekday; i++) {
            console.log(i, 'pre');
            let currD = d.setDate(d.getDate() - i).toString();
            console.log(currD);
            selectedWeek.push(currD);
        }
        for (let i = date.weekday; i < 7; i++) {
            console.log(i, 'post');
            selectedWeek.push(d.setDate(d.getDate() + i).toString());
        }
        console.log(selectedWeek);
    }

I need Sunday through Saturday date objects.

I am not using a date library so prefer vanilla javascript solutions.

Upvotes: 2

Views: 4434

Answers (4)

jabaa
jabaa

Reputation: 6737

Create an array with 7 elements, subtract the weekday and add the index as day:

function selectWeek(date) {
  return Array(7).fill(new Date(date)).map((el, idx) =>
    new Date(el.setDate(el.getDate() - el.getDay() + idx)))
}

const date = new Date();
console.log(selectWeek(date));

I'm using

fill(new Date(date))

to create a copy and not modify the argument. You can get the days of a month with the same concept:

function selectMonth(date) {
  return Array(31).fill(new Date(date)).map((el, idx) =>
    new Date(el.setDate(1 + idx))).filter(el => el.getMonth() === date.getMonth());
}

const date = new Date();
console.log(selectMonth(date));

Upvotes: 3

MMMahdy-PAPION
MMMahdy-PAPION

Reputation: 1101

Did you check Date prototypes before?

I think Date.prototype.getDay() can do what you want:

function selectWeekDays(date) {
  var i,
      d = new Date(date),
      a = [];
  // console.log(d.getDay());   // Number of the day
  d.setDate(d.getDate() - d.getDay() - 1);   // Set date one day before first day of week
  for (i=0; i<7; i++) {
    d.setDate(d.getDate() + 1);   // Add one day
    a.push(d.valueOf());
  }
  return a;
}

var result = selectWeekDays('2022-01-01') // Satureday = 6

console.log(result); 
result.forEach(e => console.log(new Date(e).toString()));

Upvotes: 0

JakeAve
JakeAve

Reputation: 376

The .getDay() gives you the day of the week.

function selectWeek(date) {
  const selectWeek = [];
  let temp = date;
  while (temp.getDay() > 0) temp.setDate(temp.getDate() - 1); // find Sunday
  // get the rest of the week in the only do while loop ever created
  do {
    selectWeek.push(new Date(temp));
    temp.setDate(temp.getDate() + 1);
  } while (temp.getDay() !== 0);

  return selectWeek;
  /* for display purposes only */
  // const dates = selectWeek.map((date) => date.toString());
  // console.log(dates);
}

selectWeek(new Date());
selectWeek(new Date("2020-01-01"));
selectWeek(new Date("december 25, 1990"));

Upvotes: 0

Gleb Kostyunin
Gleb Kostyunin

Reputation: 3863

here's how I would solve this one:

function selectWeek(date) {
        let selectWeek = [];
        for (let i=0; i<7; i++) {
          let weekday = new Date(date) // clone the selected date, so we don't mutate it accidentally.
          let selectedWeekdayIndex = date.getDay() // i.e. 5 for friday
          let selectedDay = date.getDate() // 1-31, depending on the date
          weekday.setDate(selectedDay - selectedWeekdayIndex + i)
          selectWeek = [...selectWeek, weekday]
        }
        return selectWeek;
    }

Let's take today's date as an example: 18.02.22. Friday. We do 6 iterations. On first one we get the selectedWeekdayIndex, which is 5 for friday. We clone the date and re-set it's day (18) reducing it by this number: 18-5 = 13. This is the day for Sunday. Then we go on incrementing days by one to fill the rest of the week.

Of course it can be optimised and written much shorter, but I tried to show and explain the logic.

Upvotes: 1

Related Questions