Search code examples
javascriptvariablesdatenew-operator

Get tomorrow's date with getDay Javascript


What I am making is a weather forecast website, and what I need is the days of the week (ie. "Sunday", "Monday", etc.). To get tomorrow's date I am just putting "+ 1" like someone suggested in another question, but when it get's to Saturday, it says "undefined". How do I make it so when it gets to Saturday, + 1 will loop over to Sunday? Thanks in advance!

var day=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

document.getElementById('tomorrow').innerHTML = weekday[day.getDay() + 1];
document.getElementById('twodays').innerHTML = weekday[day.getDay() + 2];
document.getElementById('threedays').innerHTML = weekday[day.getDay() + 3];

Solution

  • Use (day.getDay() + i) % 7. That will only return results between 0-6.