javascript - Getting next Monday or Thursday with moment.js -


i want date of next monday or thursday (or today if mon or thurs). moment.js works within bounds of sunday - saturday, i'm having work out current day , calculate 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, surely there's better way!

first need know in week: moment.day(), or more predictable (in spite of locale) moment().isoweekday().

you want know if today's day smaller or bigger day want. if it's bigger, want use next week. if it's smaller, can use week's monday or thursday.

const dayineed = 4; // thursday if (moment().isoweekday() <== dayineed) {    return moment().isoweekday(dayineed); } else... 

then want solution give "the monday of next week", regardless of in current week. in nutshell, want first go next week, using moment().add(1, 'weeks'). once you're in next week, can select day want, using moment().day(1).

together:

const dayineed = 4; // thursday  // if haven't yet passed day of week need: if (moment().isoweekday() <== dayineed) {    // give me week's instance of day   return moment().isoweekday(dayineed); } else {   // otherwise, give me next week's instance of day   return moment().add(1, 'weeks').isoweekday(dayineed); } 

see https://stackoverflow.com/a/27305748/800457


Comments