Javascript - get array of dates between 2 dates

后端 未结 25 1464
傲寒
傲寒 2020-11-22 15:16
var range = getDates(new Date(), new Date().addDays(7));

I\'d like \"range\" to be an array of date objects, one for each day between the two dates

25条回答
  •  春和景丽
    2020-11-22 15:55

    Using ES6 you have Array.from meaning you can write a really elegant function, that allows for dynamic Intervals (hours, days, months).

    function getDates(startDate, endDate, interval) {
    const duration = endDate - startDate;
    const steps = duration / interval;
    return Array.from({length: steps+1}, (v,i) => new Date(startDate.valueOf() + (interval * i)));
    }
    const startDate = new Date(2017,12,30);
    const endDate = new Date(2018,1,3);
    const dayInterval = 1000 * 60 * 60 * 24; // 1 day
    const halfDayInterval = 1000 * 60 * 60 * 12; // 1/2 day
    
    console.log("Days", getDates(startDate, endDate, dayInterval));
    console.log("Half Days", getDates(startDate, endDate, halfDayInterval));

提交回复
热议问题