Get next date from weekday in JavaScript

前端 未结 6 1262
心在旅途
心在旅途 2020-12-01 18:18

How can one return the next date of a given weekday (it could be either a number 0-6 or names Sunday-Saturday).

Example, if today, on Friday

6条回答
  •  悲哀的现实
    2020-12-01 18:33

    Here is another simple solution

    //takes dayIndex from sunday(0) to saturday(6)
    function nextDate(dayIndex) {
        var today = new Date();
        today.setDate(today.getDate() + (dayIndex - 1 - today.getDay() + 7) % 7 + 1);
        return today;
    }
    document.write("Next Sunday is: "+nextDate(0).toLocaleString()+"
    "); document.write("Next Thursday is: "+nextDate(4).toLocaleString()+"
    "); document.write("Next Saturday is: "+nextDate(6).toLocaleString());

提交回复
热议问题