Getting the date of next Monday

前端 未结 9 455
臣服心动
臣服心动 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));

    0 讨论(0)
  • 2020-12-02 23:42

    This will give next Monday if today is Monday

    var d = new Date();
    d.setDate(d.getDate() + (7-d.getDay())%7+1);
    

    This will result in today if today is Monday

    var d = new Date();
    d.setDate(d.getDate() + ((7-d.getDay())%7+1) % 7);
    
    0 讨论(0)
  • 2020-12-02 23:46

    Or more simple:

    let now = new Date();
    let day = 1; // Monday
    
    if (day > 6 || day < 0) 
      day = 0;
        
    while (now.getDay() != day) {
      now.setDate(now.getDate() + 1);
    }
    now.setDate(now.getDate() + 1);
    
    console.log(now); // next Monday occurrence
    
    0 讨论(0)
提交回复
热议问题