Find next instance of a given weekday (ie. Monday) with moment.js

JavascriptMomentjs

Javascript Problem Overview


I want to get the date of the next Monday or Thursday (or today if it is Mon or Thurs). As Moment.js works within the bounds of a Sunday - Saturday, I'm having to work out the current day and calculate the next Monday or Thursday based on that:

if (moment().format("dddd")=="Sunday") { var nextDay = moment().day(1); }
if (moment().format("dddd")=="Monday") { var nextDay = moment().day(1); }
if (moment().format("dddd")=="Tuesday") { var nextDay = moment().day(4); }
if (moment().format("dddd")=="Wednesday") { var nextDay = moment().day(4); }
if (moment().format("dddd")=="Thursday") { var nextDay = moment().day(4); }
if (moment().format("dddd")=="Friday") { var nextDay = moment(.day(8); }
if (moment().format("dddd")=="Saturday") { var nextDay = moment().day(8); }

This works, but surely there's a better way!

Javascript Solutions


Solution 1 - Javascript

The trick here isn't in using Moment to go to a particular day from today. It's generalizing it, so you can use it with any day, regardless of where you are in the week.

First you need to know where you are in the week: moment().day(), or the slightly more predictable (in spite of locale) moment().isoWeekday(). Critically, these methods return an integer, which makes it easy to use comparison operators to determine where you are in the week, relative to your targets.

Use that to know if today's day is smaller or bigger than the day you want. If it's smaller/equal, you can simply use this week's instance of Monday or Thursday...

const dayINeed = 4; // for Thursday
const today = moment().isoWeekday();

if (today <= dayINeed) { 
  return moment().isoWeekday(dayINeed);
}

But, if today is bigger than the day we want, you want to use the same day of next week: "the monday of next week", regardless of where you are in the current week. In a nutshell, you want to first go into next week, using moment().add(1, 'weeks'). Once you're in next week, you can select the day you want, using moment().day(1).

Together:

const dayINeed = 4; // for Thursday
const today = moment().isoWeekday();

// if we haven't yet passed the day of the week that I need:
if (today <= 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 same day
  return moment().add(1, 'weeks').isoWeekday(dayINeed);
}

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


EDIT: other commenters have pointed out that the OP wanted something more specific than this: the next of an array of values ("the next Monday or Thursday"), not merely the next instance of some arbitrary day. OK, cool.

The general solution is the beginning of the total solution. Instead of comparing for a single day, we're comparing to an array of days: [1,4]:

const daysINeed = [1,4]; // Monday, Thursday
// we will assume the days are in order for this demo, but inputs should be sanitized and sorted

function isThisInFuture(targetDayNum) {
  // param: positive integer for weekday
  // returns: matching moment or false
  const todayNum = moment().isoWeekday();  
  
  if (todayNum <= targetDayNum) { 
    return moment().isoWeekday(targetDayNum);
  }
  return false;
}

function findNextInstanceInDaysArray(daysArray) {
    // iterate the array of days and find all possible matches
    const tests = daysINeed.map(isThisInFuture);

    // select the first matching day of this week, ignoring subsequent ones, by finding the first moment object
    const thisWeek = tests.find((sample) => {return sample instanceof moment});

    // but if there are none, we'll return the first valid day of next week (again, assuming the days are sorted)
    return thisWeek || moment().add(1, 'weeks').isoWeekday(daysINeed[0]);;
}
findNextInstanceInDaysArray(daysINeed);

I'll note that some later posters provided a very lean solution that hard-codes an array of valid numeric values. If you always expect to search the same days, and don't need to generalize for other searches, that'll be the more computationally efficient solution, although not the easiest to read, and impossible to extend.

Solution 2 - Javascript

get the next monday using moment

moment().startOf('isoWeek').add(1, 'week');

Solution 3 - Javascript

moment().day() will give you a number referring to the day_of_week.

What's even better: moment().day(1 + 7) and moment().day(4 + 7) will give you next Monday, next Thursday respectively.

See more: http://momentjs.com/docs/#/get-set/day/

Solution 4 - Javascript

The following can be used to get any next weekday date from now (or any date)

var weekDayToFind = moment().day('Monday').weekday(); //change to searched day name

var searchDate = moment(); //now or change to any date
while (searchDate.weekday() !== weekDayToFind){ 
  searchDate.add(1, 'day'); 
}

Solution 5 - Javascript

Most of these answers do not address the OP's question. Andrejs Kuzmins' is the best, but I would improve on it a little more so the algorithm accounts for locale.

var nextMoOrTh = moment().isoWeekday([1,4,4,4,8,8,8][moment().isoWeekday()-1]);

Solution 6 - Javascript

Next Monday or any other day

moment().startOf('isoWeek').add(1, 'week').day("monday");

Solution 7 - Javascript

IMHO more elegant way:

var setDays = [ 1, 1, 4, 4, 4, 8, 8 ],
    nextDay = moment().day( setDays[moment().day()] );

Solution 8 - Javascript

Here's e.g. next Monday:

var chosenWeekday = 1 // Monday

var nextChosenWeekday = chosenWeekday < moment().weekday() ? moment().weekday(chosenWeekday + 7) : moment().weekday(chosenWeekday)

Solution 9 - Javascript

Here's a solution to find the next Monday, or today if it is Monday:

const dayOfWeek = moment().day('monday').hour(0).minute(0).second(0);

const endOfToday = moment().hour(23).minute(59).second(59);

if(dayOfWeek.isBefore(endOfToday)) {
  dayOfWeek.add(1, 'weeks');
}

Solution 10 - Javascript

The idea is similar to the one of XML, but avoids the if / else statement by simply adding the missing days to the current day.

const desiredWeekday = 4; // Thursday
const currentWeekday = moment().isoWeekday();
const missingDays = ((desiredWeekday - currentWeekday) + 7) % 7;
const nextThursday = moment().add(missingDays, "days");

We only go "to the future" by ensuring that the days added are between 0 and 6.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike ThrussellView Question on Stackoverflow
Solution 1 - JavascriptXMLView Answer on Stackoverflow
Solution 2 - JavascriptAshUKView Answer on Stackoverflow
Solution 3 - JavascriptGavrielView Answer on Stackoverflow
Solution 4 - JavascriptvinjenzoView Answer on Stackoverflow
Solution 5 - JavascriptDavid KirkView Answer on Stackoverflow
Solution 6 - JavascriptHams Ahmed AnsariView Answer on Stackoverflow
Solution 7 - JavascriptRangoView Answer on Stackoverflow
Solution 8 - JavascriptsoftcodeView Answer on Stackoverflow
Solution 9 - Javascriptuser1514801View Answer on Stackoverflow
Solution 10 - Javascriptomg_meView Answer on Stackoverflow