Get next date from weekday in JavaScript

前端 未结 6 1215
心在旅途
心在旅途 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:37

    To expand on user 190106's answer, this code should give you what you wanted:

    function getNextDay(day, resetTime){
      var days = {
        sunday: 0, monday: 1, tuesday: 2,
        wednesday: 3, thursday: 4, friday: 5, saturday: 6
      };
    
      var dayIndex = days[day.toLowerCase()];
      if (dayIndex !== undefined) {
        throw new Error('"' + day + '" is not a valid input.');
      }
    
      var returnDate = new Date();
      var returnDay = returnDate.getDay();
      if (dayIndex !== returnDay) {
        returnDate.setDate(returnDate.getDate() + (dayIndex + (7 - returnDay)) % 7);
      }
    
      if (resetTime) {
        returnDate.setHours(0);
        returnDate.setMinutes(0);
        returnDate.setSeconds(0);
        returnDate.setMilliseconds(0);
      }
      return returnDate;
    }
    
    alert(getNextDay('thursday', true));
    

提交回复
热议问题