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;

}

其他回答

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

我使用简单的while循环来计算日期之间

var start = new日期("01/05/2017"); var end = new Date("06/30/2017"); var newend = end.setDate(end.getDate()+1); 日期(新结束); While (start < end){ console.log(new Date(start).getTime() / 1000);// Unix时间戳格式 console.log(开始);// ISO日期格式 var newDate = start.setDate(start.getDate() + 1); start = newDate (newDate); }

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

function getDates(startDate, stopDate) {
    var dateArray = new Array();
    var currentDate = startDate;
    while (currentDate <= stopDate) {
        dateArray.push(new Date (currentDate));
        currentDate = currentDate.addDays(1);
    }
    return dateArray;
}

这里是一个功能演示http://jsfiddle.net/jfhartsock/cM3ZU/

D3js提供了很多方便的函数,包括d3。是时候简单地处理日期了

https://github.com/d3/d3-time

针对您的具体要求:

Utc

var range = d3.utcDay.range(new Date(), d3.utcDay.offset(new Date(), 7));

或当地时间

var range = d3.timeDay.range(new Date(), d3.timeDay.offset(new Date(), 7));

Range将是一个日期对象数组,它位于每一天的第一个可能值上

您可以将timeDay更改为timeHour, timmonth等,在不同的间隔上获得相同的结果