Javascript - get array of dates between 2 dates

后端 未结 25 1468
傲寒
傲寒 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:40

    Note: I'm aware this is slightly different than the requested solution, but I think many will find it useful.

    If you want to find each "x" intervals (days, months, years, etc...) between two dates, moment.js and the moment-range extension packages enable this functionality.

    For example, to find each 30th day between two dates:

    window['moment-range'].extendMoment(moment);
    
    var dateString = "2018-05-12 17:32:34.874-08";
    var start  = new Date(dateString);
    var end    = new Date();
    var range1 = moment.range(start, end);
    var arrayOfIntervalDates = Array.from(range1.by('day', { step: 30 }));
    
    arrayOfIntervalDates.map(function(intervalDate){
      console.log(intervalDate.format('YY-M-DD'))
    });
    

提交回复
热议问题