Search code examples
javascriptweekday

get next 6 weedays Issue, Javascript


I need the next 6 weekdays starting from today. The term getDay() gives me a value between 0-6. If I simple add +1 every next day, I get at a certain day values which are not in the Array, how can i fix this issue? (Everything after 6 is undefined).

var d = new Date();
var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; 
                        
        document.getElementById("day0").innerHTML = weekday[d.getDay()];
                
        document.getElementById("day1").innerHTML = weekday[d.getDay()+1];
       
        document.getElementById("day2").innerHTML = weekday[d.getDay()+2];
        
        document.getElementById("day3").innerHTML = weekday[d.getDay()+3];
        
        document.getElementById("day4").innerHTML = weekday[d.getDay()+4];
        
        document.getElementById("day5").innerHTML = weekday[d.getDay()+5];
        
        document.getElementById("day6").innerHTML = weekday[d.getDay()+6];
         ```

Solution

  • You need modulo operator. Try like:

    next day = weekday[(currentDay+6) % weekday.length];