【问题标题】:How to return an array of all the dates between two selected dates using javascript如何使用javascript返回两个选定日期之间所有日期的数组
【发布时间】:2016-07-12 21:42:09
【问题描述】:

对于我的课堂作业,我需要返回日历上两个选定日期之间的日期数组(到达和离开)。

我得到了两组可以使用的代码,但是我不知道如何将它们链接在一起。

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

【问题讨论】:

  • 如果getDates 将提供给定范围内的所有日期,您所要做的就是生成一个开始日期和一个结束日期,然后使用这两个值调用getDates。仅供参考,没有人会为你做功课,所以你需要展示你为尝试解决它所做的工作。
  • 做好功课! :X
  • 谢谢你们的回复 :) 我会做我的!

标签: javascript arrays date


【解决方案1】:

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

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

【讨论】:

  • 赞成,因为这是您的第一个答案并且很有帮助,但建议不要简单地给人们作业答案:)
  • 建议使用 Date 构造函数解析字符串也不好,最好使用库或小函数或以其他方式生成日期。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-26
  • 2011-05-23
  • 1970-01-01
  • 1970-01-01
  • 2016-01-04
  • 1970-01-01
相关资源
最近更新 更多