how to get next week date in javascript

前端 未结 7 1494
不知归路
不知归路 2020-12-08 19:21

Does anyone know how can I get next week date based on this week date? example if I have this thursday date (25/6/2009) how can I use javascript to get next thursday date (2

相关标签:
7条回答
  • 2020-12-08 19:56

    Function that returns next weekdaay:

    function getNextWeekDay (startDate, dayOfWeek){
        var dayOffset = dayOfWeek > startDate.getDay()
            ? dayOfWeek - startDate.getDay()
            : dayOfWeek - startDate.getDay() + 7;
    
        startDate.setDate(startDate.getDate() + dayOffset);
    
        return startDate;
    }
    
    var now = new Date();
    
    var nextMonday = getNextWeekDay(new Date(),1); // 0 = Sunday, 1 = Monday, ...
    var nextSaturday = getNextWeekDay(new Date(),6);
    var nextSunday = getNextWeekDay(new Date(),0);
    var secondNextMonday = getNextWeekDay(new Date(now.getTime() + ( 7 *24 * 60 * 60 * 1000)),1);
    alert(nextMonday+ '- '+nextSaturday+ '- '+nextSunday+ '- '+secondNextMonday);
    
    0 讨论(0)
  • 2020-12-08 20:02

    An even more straightforward solution is

    let nextWeek = new Date()
    nextWeek.setDate(nextWeek.getDate() + 7)
    

    Note that it preserves the current time of day.

    0 讨论(0)
  • 2020-12-08 20:04
    function nextweek(){
        var today = new Date();
        var nextweek = new Date(today.getFullYear(), today.getMonth(), today.getDate()+7);
        return nextweek;
    }
    
    0 讨论(0)
  • 2020-12-08 20:04
    Date.prototype.addDays = function (d) {
        if (d) {
            var t = this.getTime();
            t = t + (d * 86400000);
            this.setTime(t);
        }
    };
    
    this_week.addDays(7);
    
    0 讨论(0)
  • 2020-12-08 20:07
    var firstDay = new Date("2009/06/25");
    var nextWeek = new Date(firstDay.getTime() + 7 * 24 * 60 * 60 * 1000);
    

    You can also look at DateJS if you like "fluent" APIs.

    0 讨论(0)
  • 2020-12-08 20:07

    function dateObject.getNextWeekDay returns the next weekday after the object's own date.

    Date.prototype.getNextWeekDay = function(d) {
      if (d) {
        var next = this;
        next.setDate(this.getDate() - this.getDay() + 7 + d);
        return next;
      }
    }
    
    var now = new Date();
    var nextMonday = now.getNextWeekDay(1); // 0 = Sunday, 1 = Monday, ...
    var secondNextMonday = new Date(nextMonday).getNextWeekDay(1);
    console.log('Next Monday : ' + nextMonday);
    console.log('Second Next Monday : ' + secondNextMonday);

    0 讨论(0)
提交回复
热议问题