'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 fromDate by 1 until it reaches the toDate?

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(1, 'days');

    while(startDate.format('M/D/YYYY') !== endDate.format('M/D/YYYY')) {
      console.log(startDate.toDate());
      dates.push(startDate.toDate());
      startDate = startDate.add(1, 'days');
    }

    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.



Solution 1:[1]

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 2:[2]

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 3:[3]

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>

Solution 4:[4]

Momentjs doesn't provide this by itself but there is a plugin which offers it: moment-range.

Specifically, check out the Iteration docs.

Solution 5:[5]

As an extension of Kyle's answer - I've been trying to get this to work with Unix timestamps and after lots of trial and error I got it to work and thought I'd post it here in case anyone is seeking the same thing and needs it. See my code below:

fromDate = moment.unix(req.params.dateFrom).format('YYYY-MM-DD')
toDate = moment.unix(req.params.dateTo).format('YYYY-MM-DD')

// Returns an array of dates between the two dates
function enumerateDaysBetweenDates(startDate, endDate) {
    startDate = moment(startDate);
    endDate = moment(endDate);

    var now = startDate, dates = [];

    while (now.isBefore(endDate) || now.isSame(endDate)) {
        dates.push(now.format('YYYY-MM-DD'));
        now.add(1, 'days');
    }
    return dates;
};

Note that I convert it to Unix, then convert that value to moment again. This was the issue that I had, you need to make it a moment value again in order for this to work.

Example usage:

fromDate = '2017/03/11' // AFTER conversion from Unix
toDate = '2017/03/13' // AFTER conversion from Unix

console.log(enumerateDaysBetweenDates(fromDate, toDate));

Will return:

['2017/03/11', '2017/03/12', '2017/03/13']

Solution 6:[6]

Using ES6 notation

const from = moment('01/01/2014', 'DD/MM/YYYY')
const to   = moment('06/01/2014', 'DD/MM/YYYY')

const nbDays = to.diff(from, 'days') + 1
const result = [...Array(nbDays).keys()]
          .map(i => from.clone().add(i, 'd'))

console.log(result)
<script src="https://momentjs.com/downloads/moment.min.js"></script>

Solution 7:[7]

You can easily enumerate with moment.js Here is a more generic solution for days, weeks, months or years:

https://gist.github.com/gvko/76f0d7b4b61b18fabfe9c0cc24fc3d2a

Solution 8:[8]

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

const moment = require('moment');

 let startDate = moment('2021-12-24');
 let endDate = moment('2022-1-4');
 let date = [];

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

 console.log(date)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Pharaj Ali
Solution 3 Tyagi
Solution 4 k0pernikus
Solution 5 jock.perkins
Solution 6 Sylvain Gourio
Solution 7
Solution 8 Dez