Search code examples
javascriptdatedayofweekweek-numberweekday

How to find the days of the week in JavaScript


I am trying to find the weekdays from today to Sunday. Since today is Monday I want to display the dates from Monday till Sunday, but tomorrow, I want my programme works from Tuesday to Sunday.

dateSets() {
            let firstDayOfWeek = "";
            let dates = [];
            firstDayOfWeek = new Date();
                let sunday = new Date();
                sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
                const diff = sunday.getDate() - firstDayOfWeek.getDate();
                dates.push(new Date());
                for (let i = 0; i < diff; i++) {
                    dates.push(
                        new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + 1))
                    );
                }
            return dates;
        },

And here is the other function to find the date of the week:

getDateOfWeek(week, year) {
            let simple = new Date(year, 0, 1 + (week - 1) * 7);
            let dow = simple.getDay();
            let weekStart = simple;
            if (dow <= 4) weekStart.setDate(simple.getDate() - simple.getDay() + 1);
            else weekStart.setDate(simple.getDate() + 8 - simple.getDay());
            return weekStart;
        },

But it doesn't work that I expected, in dataset, only Monday is being displayed but not other dates and I don't understand the reason. If you can help me with this, I would be really glad. Thanks...


Solution

  • function getWeekDates(){
      const dates = [new Date()]; // today
      const curr = new Date();
      const remDaysCount = 7-curr.getDay();
      for(let i=1; i<= remDaysCount; i++){
        // increase current Date by 1 and set to current Date
          const nextDate = curr.setDate(curr.getDate()+1);
        dates.push(new Date(nextDate));
      }
      return dates;
    }
    
    console.log(getWeekDates());