简体   繁体   中英

Get all dates in a array between selecteddaterange from ngxdaterangepicker calendar in angular

Here's what I tried. I want to get dates between selected enddate and startdate in an array. So that I can plot the graph between dates and number of calls .

enumerateDaysBetweenDates(startDate, endDate) {
    const dates = [];
    const currDate = moment(startDate).startOf('day');
    const lastDate = moment(endDate).startOf('day');

    while(currDate.add(1, 'days').diff(lastDate) < 0) {
        dates.push(currDate.clone().toDate());
    }
    console.log(dates[0]);
    return dates; 

Use this https://github.com/rotaready/moment-range

import { extendMoment } from 'moment-range';  
const range = moment.range(start, end);

You can set the function like that

function enumerateDaysBetweenDates(startDate, endDate) {
    let dates = [];
    while(startDate.getTime() <= endDate.getTime()) {
        let initDate = new Date(startDate);
        dates.push(initDate.getDay() + '/' + (initDate.getMonth() + 1) + '/' + initDate.getYear());       
        startDate.setTime(startDate.getTime() + 24*60*60*1000); // adding one day
    }
    return dates;
}

and use it like this

enumerateDaysBetweenDates(new Date('2019-11-12'),new Date('2019-11-20'));

and its result will be

0: Tue Nov 12 2019 03:00:00 GMT+0300 (GMT+03:00) {}
1: Wed Nov 13 2019 03:00:00 GMT+0300 (GMT+03:00) {}
2: Thu Nov 14 2019 03:00:00 GMT+0300 (GMT+03:00) {}
3: Fri Nov 15 2019 03:00:00 GMT+0300 (GMT+03:00) {}
4: Sat Nov 16 2019 03:00:00 GMT+0300 (GMT+03:00) {}
5: Sun Nov 17 2019 03:00:00 GMT+0300 (GMT+03:00) {}
6: Mon Nov 18 2019 03:00:00 GMT+0300 (GMT+03:00) {}
7: Tue Nov 19 2019 03:00:00 GMT+0300 (GMT+03:00) {}
8: Wed Nov 20 2019 03:00:00 GMT+0300 (GMT+03:00) {}

No need for moment, use Array.from with a length of how many days you want and a constructor function that adds the index to start date.

 const msInDay = 1000 * 3600 * 24; // Number of milliseconds in a day const enumerateDaysBetweenDates = (startDate, endDate) => Array.from( { length: (endDate.getTime() - startDate.getTime()) / msInDay + 1 }, (_, index) => new Date(startDate.getTime() + (index * msInDay)) ); console.log(enumerateDaysBetweenDates(new Date('2019-01-23'), new Date('2019-01-28')));

Moment is quite a bloated library and it is not tree shakable so you get the lot even if you use a very small part of the library. It is also not functional so

currDate.add(1, 'days')

mutates currDate so each iteration of your loop currDate moves one day ahead. You need to clone currDate on each loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM