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

2019-01-18 09:44发布

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!

8条回答
Anthone
2楼-- · 2019-01-18 10:18

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.

查看更多
Viruses.
3楼-- · 2019-01-18 10:19

get the next monday using moment

moment().startOf('isoWeek').add(1, 'week');
查看更多
登录 后发表回答