How to enumerate dates between two dates in Moment

Solution 1:

.add() is a mutator method, so the assignment in this line is unnecessary:

startDate = startDate.add(1, 'days');

You can just do this, and have the same effect:

startDate.add(1, 'days');

While it's name would imply the creation of a new Date object, the toDate() method really just returns the existing internal Date object.

So, none of your method calls are creating new Date or moment object instances. Fix that by using .clone() to get a new instance:

startDate = startDate.clone().add(1, 'days');

Or better yet, wrap the values in a call to moment() as Mtz suggests in a comment, and it will clone the instance, if the value is a moment object, or it will parse the input to create a new moment instance.

startDate = moment(startDate).add(1, 'days');

I think a date enumerator method should not change either of the arguments passed in. I'd create a separate variable for enumerating. I'd also compare the dates directly, rather than comparing strings:

var enumerateDaysBetweenDates = function(startDate, endDate) {
    var dates = [];

    var currDate = moment(startDate).startOf('day');
    var lastDate = moment(endDate).startOf('day');

    while(currDate.add(1, 'days').diff(lastDate) < 0) {
        console.log(currDate.toDate());
        dates.push(currDate.clone().toDate());
    }

    return dates;
};

Solution 2:

Got it for you:

var enumerateDaysBetweenDates = function(startDate, endDate) {
    var now = startDate.clone(), dates = [];

    while (now.isSameOrBefore(endDate)) {
        dates.push(now.format('M/D/YYYY'));
        now.add(1, 'days');
    }
    return dates;
};

Referencing now rather than startDate made all the difference.

If you're not after an inclusive search then change .isSameOrBefore to .isBefore

Fiddle: http://jsfiddle.net/KyleMuir/sRE76/118/

Solution 3:

use moment and work with while loop, code will run in loop untill startDate is equal to endDate and push startDate and then increment it with 1 day so can get next date

function enumerateDaysBetweenDates (startDate, endDate){
  let date = []
  while(moment(startDate) <= moment(endDate)){
    date.push(startDate);
    startDate = moment(startDate).add(1, 'days').format("YYYY-MM-DD");
  }
  return date;
}

you can test it by calling function like this

let dateArr = enumerateDaysBetweenDates('2019-01-01', '2019-01-10');

Solution 4:

Using moment library and for loop you can enumerate between two dates.

let startDate = moment('2020-06-21');
let endDate = moment('2020-07-15');
let date = [];

for (var m = moment(startDate); m.isBefore(endDate); m.add(1, 'days')) {
    date.push(m.format('YYYY-MM-DD'));
}

console.log(date)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>