如何使用javascript返回两个选定日期之间所有日期的数组

时间:2016-07-12 21:42:09

标签: javascript arrays date

对于我的课程作业,我需要在日历上的两个选定日期(到达和离开)之间返回一系列日期。

我可以使用两组代码,但是我无法弄清楚如何将它们链接在一起。

var arrival = document.getElementById('arrivalDate');
console.log(arrival.value);

var checkout = document.getElementById('departureDate');
console.log(checkout.value);

// Figure out the number of days they are check in for.
var days = checkout.value.split('-')[2] - arrival.value.split('-')[2];
console.log(days);

function dateRange(arrival, days) {
  range = [];

  // Starting At

  return range;
}
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate) {
  var dates = [],
      currentDate = startDate,
      addDays = function(days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
      };
  while (currentDate <= endDate) {
    dates.push(currentDate);
    currentDate = addDays.call(currentDate, 1);
  }
  return dates;
};

// Usage
var dates = getDates(new Date(2013,10,22), new Date(2013,11,25));                                                                                                           
dates.forEach(function(date) {
  console.log(date);
});

1 个答案:

答案 0 :(得分:1)

当你已经得到答案时,似乎很简单!

var arrivalDate = new Date(document.getElementById('arrivalDate').value);
var departureDate = new Date(document.getElementById('departureDate').value);
var dateRange = getDates(arrivalDate, departureDate);