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!
The following can be used to get any next weekday date from now (or any date)
Here's a solution to find the next Monday, or today if it is Monday:
Here's e.g. next Monday:
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()
.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...
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, usingmoment().day(1)
.Together:
See also https://stackoverflow.com/a/27305748/800457
moment().day()
will give you a number referring to the day_of_week.What's even better:
moment().day(1 + 7)
andmoment().day(4 + 7)
will give you next Monday, next Thursday respectively.See more: http://momentjs.com/docs/#/get-set/day/
IMHO more elegant way: