Javascript - get array of dates between 2 dates

后端 未结 25 1657
傲寒
傲寒 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:50

    Date.prototype.addDays = function(days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
    }
    
    function getDates(startDate, stopDate) {
        var dateArray = new Array();
        var currentDate = startDate;
        while (currentDate <= stopDate) {
            dateArray.push(new Date (currentDate));
            currentDate = currentDate.addDays(1);
        }
        return dateArray;
    }
    

    Here is a functional demo http://jsfiddle.net/jfhartsock/cM3ZU/

提交回复
热议问题