How to get next seven days from X and format in JS

前端 未结 6 2232
渐次进展
渐次进展 2020-12-06 19:25

I want to print something like this (a 7-day calendar) but with the ability to start from any date I want.

Monday, 1 January 2011
Tuesday, 2 January 2011
Wed         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 20:22

    An initial date:

    var startingDay = new Date(year, month, day);
    

    A whole week from startingDay:

    var thisDay = new Date();
    for(var i=0; i<7; i++) {
      thisDay.setDate(startingDay.getDate() + i);
      console.log(thisDay.format());
    }
    

    The formatting function:

    Date.prototype.format = function(){
        var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];        
        var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
        return days[this.getDay()]
              +", "
              +this.getDate()
              +" "
              +months[this.getMonth()] 
              +" "
              +this.getFullYear();
    };
    

提交回复
热议问题