Skip to content Skip to sidebar Skip to footer

Get Array Of Dates Given 2 Dates Using Momentjs In Reactjs

Currently i'm importing Moment and Moment range as below, Need the array of dates between given 2 dates so that dates can be iterated import Moment from 'moment'; import {extendMom

Solution 1:

You can clone the start date and add one day at a time, pushing a formatted date to an array.

By using a while loop and isBefore you can ensure you keep iterating until you're at the end date.

You might want to make sure this behaves correctly at the boundaries of your start and end. I.e.: do you want it to include or exclude the input days?

const start = moment("2018-10-14", 'YYYY-MM-DD');
const end = moment("2018-10-20", 'YYYY-MM-DD');

const current = start.clone();
const result = [];

while (current.isBefore(end)) {
  result.push(current.format("YYYY-MM-DD"));
  current.add(1, "day");
}

console.log(result);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Solution 2:

To do what you are asking since you already have moment-range you would do something like this:

constrange = moment.range(moment("2018-10-14"), moment("2018-10-20"));

console.log(Array.from(range.by('day')).map(x => x.format('YYYY-MM-DD')))

If you do not need to format right away it would simply be:

Array.from(range.by('day'))  // for your range

Here is an example in node but it would be similar in your case just import by

Post a Comment for "Get Array Of Dates Given 2 Dates Using Momentjs In Reactjs"