moment js: get days between period

Viewed 1610

I have a period of 6 days between 2 iso strings:

const period = {
start: "2020-07-19T22:00:00.000Z",
end: "2020-07-25T22:00:00.000Z"
}

I'd like to have the 6 different days of the week included into this period like

 [
'monday',
'tuesday',
'wednesday',
 etc
]

So far this is what I came up with:

const days = [];
    for (let i = 0; i < 6; i++) {
      const day = moment(this.period.start).add(i, 'days');
      days.push(moment(day).day());
    }

Is there a simple/elegant way to do this with moment.js?

2 Answers

        var period = {
            start: "2020-07-19T22:00:00.000Z",
            end: "2020-07-25T22:00:00.000Z"
        }
        var i = 0;
        var dates = [];
        while (i < moment(period.end).diff(period.start, 'days')) {

            var date = moment(period.start).add(i, 'days').format('dddd');
            dates.push(date);
            i++;
        }
        document.getElementById('div').innerHTML = JSON.stringify(dates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.0/moment.min.js"></script>
 <div id="div"></div>

You can possibly use this approach that will create an array from the difference between the two dates in days, then a .map() call on it where you can take advantage of the index to add days to the start date and get the right format.

const period = {
    start: "2020-07-19T22:00:00.000Z",
    end: "2020-07-25T22:00:00.000Z"
};
const startDate = moment(period.start);
const endDate = moment(period.end);
const days = new Array(endDate.diff(startDate, 'days')).fill(null)
             .map((v, index) => (
                 startDate.clone().add(index, 'days').format('dddd')
             ));
             
console.log(days);
<script src="https://momentjs.com/downloads/moment.min.js"></script>

Related