Wednesday, September 11, 2013

Incrementing date to next friday

Saw this on google+ and here is my explanation on how to do it. It should be easy enough to alter the code for any other day, but the question wanted it to go to friday so here is my explanation:

tricky one, but doable. You do want to get the number day, but setting date may not work because of the end of the month...

so get the day:

var date = new Date();
var day = date.getDay();

now we need to normalize those numbers to see how many days forward we need to move. Friday is day 5, but we really want it at day 7 (or 0). so we add 2 and take the modulus of 7.

var normalizedDay = (day + 2) % 7;


now we have the days of the week where we want them. the number of days to go forward by will be 7 minus the normaized day:

var daysForward = 7 - normalizedDay;


if you don't want friday to skip to the next friday then take the modulus of 7 again. Now we just add that many days to the date:

var nextFriday = new Date(+date + (daysForward * 24 * 60 * 60 * 1000));


if you want the start of the day then you have to turn back the hours, minutes and milliseconds to zero:

nextFriday.setHours(0);
nextFriday.setMinutes(0);
nextFriday.setMilliseconds(0);

or for the lazy:

jumpToNextFriday = function(date) {
  return new Date(+date+(7-(date.getDay()+2)%7)*86400000);
}

4 comments:

  1. Very nice tutorial! I was wondering if it's possible to add an hour to that? Let's say i wanted to return the next friday at 9 o'clock in the morning?

    ReplyDelete
    Replies
    1. This comment seems to have been removed. I was curious as to what you had suggested on this question returning the next fridat at 9 'o clock?

      Delete
    2. The previous comment was spam so I removed it. If you wanted 9 in the morning you just need to change the setHours(0) to setHours(9)

      Delete