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

后端 未结 10 1056
旧巷少年郎
旧巷少年郎 2020-12-02 15:36

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

10条回答
  •  [愿得一人]
    2020-12-02 15:50

    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.

提交回复
热议问题