doremi doremi - 2 months ago 6x
Javascript Question

How to enumerate dates between two dates in Moment

I have two moment dates:

var fromDate = moment(new Date('1/1/2014'));
var toDate = moment(new Date('6/1/2014'));

Does moment provide a way to enumerate all of the dates between these two dates?

If not, is there any better solution other than to make a loop which increments the
by 1 until it reaches the

Edit: Adding date enumeration method and problem

I've mocked up a method for enumerating the days between two dates, but I'm running into an issue.

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

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

while(startDate.format('M/D/YYYY') !== endDate.format('M/D/YYYY')) {
startDate = startDate.add('days', 1);

return dates;

Take a look at the output when I run
enumerateDaysBetweenDates( moment(new Date('1/1/2014')), moment(new Date('1/5/2014'));

Thu Jan 02 2014 00:00:00 GMT-0800 (PST)
Fri Jan 03 2014 00:00:00 GMT-0800 (PST)
Sat Jan 04 2014 00:00:00 GMT-0800 (PST)
[ Sun Jan 05 2014 00:00:00 GMT-0800 (PST),
Sun Jan 05 2014 00:00:00 GMT-0800 (PST),
Sun Jan 05 2014 00:00:00 GMT-0800 (PST) ]

It's console.logging the right dates, but only the final date is being added to the array. How/why is this? This smells like some sort of variable reference issue - but I'm not seeing it.


.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');

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 = startDate.clone().startOf('day');
    var lastDate = endDate.clone().startOf('day');

    while(currDate.add(1, 'days').diff(lastDate) < 0) {

    return dates;