Javascript - get array of dates between 2 dates

后端 未结 25 1166
傲寒
傲寒 2020-11-22 15:16
var range = getDates(new Date(), new Date().addDays(7));

I\'d like \"range\" to be an array of date objects, one for each day between the two dates

25条回答
  •  醉酒成梦
    2020-11-22 15:45

    @softvar's solution, but then including working dates option

    /**
     * Returns array of working days between two dates.
     *
     * @param {string} startDate
     *   The start date in yyyy-mm-dd format.
     * @param {string} endDate
     *   The end date in yyyy-mm-dd format.
     * @param {boolean} onlyWorkingDays
     *   If true only working days are returned. Default: false
     *
     * @return {array}
     *   Array of dates in yyyy-mm-dd string format.
     */
    function getDates(startDate, stopDate, onlyWorkingDays) {
      let doWd = typeof onlyWorkingDays ==='undefined' ? false : onlyWorkingDays;
    
      let dateArray = [];  
      let dayNr;
      let runDateObj = moment(startDate);  
      let stopDateObj = moment(stopDate);
    
      while (runDateObj <= stopDateObj) {
        dayNr = runDateObj.day();
        if (!doWd || (dayNr>0 && dayNr<6)) {
         dateArray.push(moment(runDateObj).format('YYYY-MM-DD'));  
        }
    
        runDateObj = moment(runDateObj).add(1, 'days');
      }
      return dateArray;
    }
    

提交回复
热议问题