Get next date from weekday in JavaScript

Иван Грозный picture Иван Грозный · Oct 16, 2009 · Viewed 22.5k times · Source

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 16-Oct-2009 I passed in:

  • Friday, it would return today's date 16-Oct-2009
  • Saturday returns 17-Oct-2009
  • Thursday returns 22-Oct-2009

Answer

Tim picture Tim · Oct 16, 2009

Just adding 7 doesn't solve the problem.

The below function will give you the next day of the week.

function nextDay(x){
    var now = new Date();    
    now.setDate(now.getDate() + (x+(7-now.getDay())) % 7);
    return now;
}