-3

Get the date list based on start and end date using moment js.

For example, I have two dates, One is a start date and end date. My start date is 2019-04-02 and my end date is 2019-05-16 I need all the date in between these two dates.

My output will be ["2019-04-02", "2019-04-03", "2019-04-04", ..., "2019-05-16"] is it possible in moment js ?

Joey Phillips
  • 1,543
  • 2
  • 14
  • 22
achu
  • 639
  • 2
  • 10
  • 26
  • Do you already have a data on which you want to apply start and end date or you just want to generate an array of dates between two given dates ? – Utsav Patel Apr 01 '19 at 09:55
  • There's a high activity question from ~5 years prior, asking the exact same thing (with better "this is what I tried" question) https://stackoverflow.com/questions/23795522/how-to-enumerate-dates-between-two-dates-in-moment – Daryn Jan 24 '21 at 08:15

4 Answers4

6

This should work, but for the next time remember to add what you tried, before posting a question

var day1 = moment("2019-05-01");
var day2 = moment("2019-04-06");
var result = [moment({...day2})];

while(day1.date() != day2.date()){
  day2.add(1, 'day');
  result.push(moment({ ...day2 }));  
}
console.log(result.map(x => x.format("YYYY-MM-DD")));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
Federico Galfione
  • 1,069
  • 7
  • 19
2

    var dates = [];
    var startDate = moment('2019-04-02', 'YYYY-MM-DD');
    dates.push(startDate.format('YYYY-MM-DD'));          
    while(!startDate.isSame('2019-05-16')){
        startDate = startDate.add(1, 'days');
        dates.push(startDate.format('YYYY-MM-DD'));
    }

    console.log(dates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>
Solomon Tam
  • 739
  • 3
  • 11
1

Something like the following would work. We set our start and end date, create an empty array and loop through the days by adding a day per iteration, and adding the current day to our list.

var start = moment("2019-01-01")
var end = moment("2019-01-30");

var list = [];

for (var current = start; current <= end; current.add(1, 'd')) {
    list.push(current.format("YYYY-MM-DD"))
}
amazonic
  • 246
  • 1
  • 7
1
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;

};