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

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

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


当前回答

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;

}

其他回答

我使用这个函数

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;
}
var boxingDay = new Date("12/26/2010");
var nextWeek  = boxingDay*1 + 7*24*3600*1000;

function getDates( d1, d2 ){
  var oneDay = 24*3600*1000;
  for (var d=[],ms=d1*1,last=d2*1;ms<last;ms+=oneDay){
    d.push( new Date(ms) );
  }
  return d;
}

getDates( boxingDay, nextWeek ).join("\n");
// Sun Dec 26 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Mon Dec 27 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Tue Dec 28 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Wed Dec 29 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Thu Dec 30 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Fri Dec 31 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Sat Jan 01 2011 00:00:00 GMT-0700 (Mountain Standard Time)

这是另外几行使用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 " > < /脚本>

使用lodash和moment:

const startDate = moment();
_.range(0, 7).map((d) => startDate.clone().add(d, 'day').toDate())

我在使用上面的答案时遇到了麻烦。由于当地夏令时(DST)导致时区偏移,日期范围丢失了一天。我实现了一个使用UTC日期的版本,解决了这个问题:

函数daterrange (startDate, endDate, steps = 1) { const dateArray = []; let currentDate = new Date(startDate); while (currentDate <=新日期(endDate)) { dateArray。推动(新日期(currentDate)); //使用UTC日期防止时区和夏令时出现问题 currentDate.setUTCDate() + steps); } 返回dateArray; } const dates = dateRange('2020-09-27', '2020-10-28'); console.log(日期);

注意:是否应用了某个时区或DST,完全取决于您的地区。忽略这一点通常不是一个好主意。使用UTC日期可以缓解大多数与时间相关的问题。

好处:您可以使用可选的steps参数设置要创建时间戳的时间间隔。如果你想要每周的时间表,将步骤设置为7。