views:

342

answers:

3

Dear coding gurus,

would you be so kind and tell me if this is possible in JavaScript to return the next date of given weekday (it could be either a number 0-6 or names Sunday-Saturday).

Example, if today, on 16-Oct-2009 I passed in:

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

Thanks, I really hope to get an answer and people, who search for this kind of function on-line would end up here, since I haven't found anything else out there that solves this. This, indeed ain't rent-a-coder, because the solution is accessible to everyone for free! I don't think you need to comment if you don't know the answer, I do, however, appreciate your comments (@Andy & @Josh).

+3  A: 

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;
}
Tim
+2  A: 

To expand on user 190106's answer, this code should give you what you wanted:

function getNextDay(day, resetTime){
  var days = {
    sunday: 0, monday: 1, tuesday: 2,
    wednesday: 3, thursday: 4, friday: 5, saturday: 6
  };

  var dayIndex = days[day.toLowerCase()];
  if (!dayIndex) {
    throw new Error('"' + day + '" is not a valid input.');
  }

  var returnDate = new Date();
  var returnDay = returnDate.getDay();
  if (dayIndex !== returnDay) {
    returnDate.setDate(returnDate.getDate() + (dayIndex + (7 - returnDay)) % 7);
  }

  if (resetTime) {
    returnDate.setHours(0);
    returnDate.setMinutes(0);
    returnDate.setSeconds(0);
    returnDate.setMilliseconds(0);
  }
  return returnDate;
}

alert(getNextDay('thursday', true));
brianpeiris
+2  A: 

A swiss-knife tool for javascript DateTime programming.

http://www.datejs.com/

this. __curious_geek