var range = getDates(new Date(), new Date().addDays(7));

我想“范围”是一个日期对象的数组,一个为两个日期之间的每一天。

诀窍在于它还应该处理月份和年份的边界。


当前回答

注意:我知道这与要求的解决方案略有不同,但我认为许多人会发现它很有用。

如果你想找到两个日期之间的每个“x”间隔(天、月、年等等),moment.js和moment-range扩展包可以实现这个功能。

例如,要找出两个日期之间的每个30天:

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'))
});

其他回答

getDates = (from, to) => {
    const cFrom = new Date(from);
    const cTo = new Date(to);

    let daysArr = [new Date(cFrom)];
    let tempDate = cFrom;

    while (tempDate < cTo) {
        tempDate.setUTCDate(tempDate.getUTCDate() + 1);
        daysArr.push(new Date(tempDate));
    }

    return daysArr;
}
function (startDate, endDate, addFn, interval) {

 addFn = addFn || Date.prototype.addDays;
 interval = interval || 1;

 var retVal = [];
 var current = new Date(startDate);

 while (current <= endDate) {
  retVal.push(new Date(current));
  current = addFn.call(current, interval);
 }

 return retVal;

}

这是另外几行使用date-fns库的解决方案:

const {format, differenceInDays, addDays} = dateFns; const getRangeDates = (startDate, endDate) => { const days = differenceInDays(endDate, startDate); console.log([…数组(天+ 1). keys ()] . map ((i) = >格式(addDays (startDate可以,我),YYYY-MM-DD))); }; getRangeDates (' 2021-06-01 ', ' 2021-06-05 '); < script src = " https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js " > < /脚本>

使用ES6,你有Array.from意味着你可以写一个非常优雅的函数,它允许动态间隔(小时,天,月)。

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));

我使用这个函数

function getDatesRange(startDate, stopDate) {
    const ONE_DAY = 24*3600*1000;
    var days= [];
    var currentDate = new Date(startDate);
    while (currentDate <= stopDate) {
        days.push(new Date (currentDate));
        currentDate = currentDate - 1 + 1 + ONE_DAY;
    }
    return days;
}