js calculates all dates between two dates

There are several situations as follows:

1. The start date is less than the end date

Year-to-month: For example, 2016-12-30 to 2017-06-12
does not span the year or month: 2017-01-02 to 2017-06-12
does not span the year or month: 2017-06-01 to 2017-06-12
2. The two dates are equal, the number of days is 0, and there is no date in between
3. The start date is less than the end date, the number of days is 0, and there is no date in between

PS : The only pitfall is that the parameter of new Date() month is between 0 and 11. That is, if you want to set the month to August, the parameter should be 7.

  /**
   **datestr:形如‘2017-06-12’的字符串
  **return Date 对象
   **/
   function getDate (datestr) {
    
    
        var temp = datestr.split("-");
        if (temp[1] === '01') {
    
    
            temp[0] = parseInt(temp[0],10) - 1;
            temp[1] = '12';
        } else {
    
    
            temp[1] = parseInt(temp[1],10) - 1;
        }
        //new Date()的月份入参实际都是当前值-1
        var date = new Date(temp[0], temp[1], temp[2]);
        return date;
    }
  /**
  ***获取两个日期间的所有日期
  ***默认start<end
  **/
  function getDiffDate (start, end) {
    
    
        var startTime = getDate(start);
        var endTime = getDate(end);
        var dateArr = [];
        while ((endTime.getTime() - startTime.getTime()) > 0) {
    
    
            var year = startTime.getFullYear();
            var month = (startTime.getMonth()+1).toString().length === 1 ? "0" + (parseInt(startTime.getMonth().toString(),10) + 1) : (startTime.getMonth() + 1);
            var day = startTime.getDate().toString().length === 1 ? "0" + startTime.getDate() : startTime.getDate();
            dateArr.push(year + "-" + month + "-" + day);
            startTime.setDate(startTime.getDate() + 1);
        }
        return dateArr;
    }

Methods used:
getTime() : Returns the number of milliseconds from January 1, 1970 to the present.
getDate(): return the date, a certain day of the month
setDate(): set the date, a certain day of the month

Guess you like

Origin blog.csdn.net/weixin_42342065/article/details/128546895