Le Qs Le Qs - 10 months ago 47
Javascript Question

Getting an array of days five days into the future fails

I am using moment js to get the date five days into the future with this code

//current date
var cd = moment().format("DD-MM-YYYY");
//5 days into the future
var nd = moment(cd, "DD-MM-YYYY").add(5, 'days').format('DD-MM-YYYY');
//get all dates from today to 5 days into the future


and now i am attempting to get an array of days between
current date
and
the future date
which is five days later

//current date
var cd = moment().format("DD-MM-YYYY");
//5 days into the future
var nd = moment(cd, "DD-MM-YYYY").add(5, 'days').format('DD-MM-YYYY');
//get all dates from today to 5 days into the future

console.log("start",cd);
console.log("end",nd);

var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};

// Usage
var dates = getDates(cd, nd);
dates.forEach(function(date) {
console.log(date);
});


This is the demo https://jsfiddle.net/codebreaker87/z9d5Lusv/67/

The code only generates the current date. How can i generate an array of all dates between?.

Answer Source

If you are using momentjs already, then you seem to be doubling its functinality by your own code.

Consider the following snip:

var getDates = function( cd, nd ){
    var dates = [];
    var now = cd.clone();
    for(var i = 0; i < nd.diff(cd, 'days') ; i++){
        // format the date to any needed output format here
        dates.push(now.add(i, 'days').format("DD-MM-YYYY"));
    }
    return dates;
}

var r = getDates( moment(), moment().add(10, 'days'));

// r now contains
["04-11-2016", "05-11-2016", "07-11-2016", "10-11-2016", "14-11-2016", "19-11-2016", "25-11-2016", "02-12-2016", "10-12-2016", "19-12-2016"]