Get Date of upcoming day


#1

Hi i am trying to get date of sunday or any other day say Wednesday of next week
i tried
d.getDate() + (1 + 5 - d.getDay()) % 7

but not working properly. I am confused with constant value
Any Idea, Please share


#2

To keep things simple, we’ll say Sunday is the first day of the week (since that’s the way getDay() works). So given any given day, presumably today, we get the day and from that need to figure out how many days until next week. If today is Sunday (and it is), getDay() is 0, and its 7 days until next week. If it were Monday, getDay() would be 1, and it would be 6 days. This shows that the formula for knowing days until next week is:

var daysUntilNextWeek = 7 - d.getDay();

Once you have those days, you add them to the current date to get to next week.

d.getDate() + daysUntilNextWeek;

From there you add to that what day of the week you want, like Wednesday. To make things a little simpler, we can make a map of day names to their offsets (you can see this as a reverse getDay()).

var DayOffsets = {
  SUN: 0,
  MON: 1,
  TUE: 2,
  WED: 3,
  THU: 4,
  FRI: 5,
  SAT: 6,
};

Adding that to our next week, assigning that total back to the date…

d.setDate(d.getDate() + daysUntilNextWeek + DayOffsets.WED);

Now the date represents the day of next week’s wednesday!

d.toString(); // "Wed Jan 30 2019 00:36:33 GMT-0500 (Eastern Standard Time)"