Moment js getting next date given specified week day

Here is how it works:

moment().day(1) // this monday
moment().day(-6) // last monday, think of it as this monday - 7 days = 1 - 7 = -6

Same applies in other direction:

moment().day(8) // next monday, or this monday + 7 days = 1 + 7 = 8

Your code moment().day(-1) can be explained as this Sunday - 1 day = 0 - 1 = -1 or this Saturday - 7 days = 6 - 7 = -1


The accepted answer only works if you already know whether the day in question is in this week or next week. What if you don't know? You simply need the next available Thursday following some arbitrary date?

First, you want to know if the day in question is smaller or bigger than the day you want. If it's bigger, you want to use the next week. If it's smaller, you can use the same week's Monday or Thursday.

const dayINeed = 4; // for Thursday
if (moment().isoWeekday() <= dayINeed) { 
  return moment().isoWeekday(dayINeed);
} else...

If we're past the day we want already (if for instance, our Moment is a Friday, and we want the next available Thursday), then you want a solution that will give you "the Thursday of the week following our moment", regardless of what day our moment is, without any imperative adding/subtracting. In a nutshell, you want to first go into the next week, using moment().add(1, 'weeks'). Once you're in the following week, you can select any day of that week you want, using moment().day(1).

Together, this will give you the next available day that meets your requirements, regardless of where your initial moment sits in its week:

const dayINeed = 4; // for Thursday

// if we haven't yet passed the day of the week that I need:
if (moment().isoWeekday() <= dayINeed) { 
  // then just give me this week's instance of that day
  return moment().isoWeekday(dayINeed);
} else {
  // otherwise, give me next week's instance of that day
  return moment().add(1, 'weeks').isoWeekday(dayINeed);
}

See also: https://stackoverflow.com/a/27305748/800457