Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment js: get days between period

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?

like image 522
Florent Arlandis Avatar asked Dec 19 '25 04:12

Florent Arlandis


1 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>
like image 114
Viroj Fernando Avatar answered Dec 21 '25 16:12

Viroj Fernando



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!