Getting the date of next Monday

前端 未结 9 512
臣服心动
臣服心动 2020-12-02 23:06

How can I get the next Monday in JavaScript? I can\'t find anything of this in the internet and I have also tried a lot of codes and understanding of this but I can\'t reall

9条回答
  •  没有蜡笔的小新
    2020-12-02 23:38

    If the actual day of the week you want is variable (Sunday, Thursday, ...) and you want a choice whether today could be a possible match or not, and it might be that you want to start with another date (instead of today), then this function may be useful:

    function getNextDayOfTheWeek(dayName, excludeToday = true, refDate = new Date()) {
        const dayOfWeek = ["sun","mon","tue","wed","thu","fri","sat"]
                          .indexOf(dayName.slice(0,3).toLowerCase());
        if (dayOfWeek < 0) return;
        refDate.setHours(0,0,0,0);
        refDate.setDate(refDate.getDate() + +!!excludeToday + 
                        (dayOfWeek + 7 - refDate.getDay() - +!!excludeToday) % 7);
        return refDate;
    }
    
    console.log("Next is: " + getNextDayOfTheWeek("Wednesday", false));

提交回复
热议问题