How can one return the next date of a given weekday (it could be either a number 0-6 or names Sunday-Saturday).
Example, if today, on Friday
And if you do not want do pass numbers but weekday-names (sunday - saturday) to find a future date of a certain weekday, then this helps you as well:
function getDateOfWeekday(refday){
var days = {
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
sunday: 0
};
if(!days.hasOwnProperty(refday))throw new Error(refday+" is not listed in "+JSON.stringify(days));
var currDate = new Date();
var currTimestamp = currDate.getTime();
var triggerDay = days[refday];
var dayMillDiff=0;
var dayInMill = 1000*60*60*24;
// add a day to dayMillDiff as long as the desired refday (sunday for instance) is not reached
while(currDate.getDay()!=triggerDay){
dayMillDiff += dayInMill;
currDate = new Date(currDate.getTime()+dayInMill);
}
return new Date(currTimestamp + dayMillDiff);
}
var sunday = getDateOfWeekday("sunday");
document.write("Next Sunday is at: "+sunday.toLocaleString()+"
");
var thursday = getDateOfWeekday("thursday");
thursday.setHours(0,0,0,0); // set hours/minutes/seconds and millseconds to zero
document.write("Next Thursday is at: "+thursday.toLocaleString()+" on midnight
");
var tuesday = getDateOfWeekday("tuesday");
document.write("Next Tuesday is at: "+tuesday.toLocaleString()+"
");