javascript - 使用简化方法生成两个给定日期之间的一系列日期

标签 javascript date

我需要生成两个给定日期之间的所有日期的序列。然而我无法获得想要的输出。

我尝试使用下面的代码。我得到一个空数组。

function getDates(startDate, endDate) {
  var dates = [];
  var currentDate = new Date(startDate);

  while (currentDate <= endDate) {
    var final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
    dates.push(final);
    currentDate = currentDate.setDate(currentDate.getDate() + 1);
  }
  return dates;
};

当我执行console.log(getDates("2019-10-10","2019-11-20"))时,我得到的结果为空数组。结果我没有得到一系列日期。

最佳答案

正如@RobG提到的,解析日期可以 yield different results因此考虑使用以下内容:

function parseDate(input) {
  var parts = input.split('-');
  return new Date(parts[0], parts[1] - 1, parts[2]);
}

function getDates(startDate, endDate) {
  var dates = [];
  var currentDate = parseDate(startDate);
  endDate = parseDate(endDate);

  while (currentDate <= endDate) {
    var final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
    dates.push(final);
    currentDate.setDate(currentDate.getDate() + 1);
  }
  return dates;
}

console.log(getDates("2019-10-10", "2019-11-20"));

<小时/>

原始答案:

您可以将 endDate 更改为 Date 类型,而不设置 currentDate,因为 setDate 会为您执行此操作:

function getDates(startDate, endDate) {
  var dates = [];
  var currentDate = new Date(startDate);
  endDate = new Date(endDate);

  while (currentDate <= endDate) {
    var final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
    dates.push(final);
    currentDate.setDate(currentDate.getDate() + 1);
  }
  return dates;
}

console.log(getDates("2019-10-10", "2019-11-20"));

关于javascript - 使用简化方法生成两个给定日期之间的一系列日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57882475/

相关文章:

java - 使用日期更改按钮的文本

javascript模板继承

javascript - 在 HTML 的 &lt;script&gt; src 属性中传递 Javascript 全局变量

javascript - 如何使用顺风向表格添加间距

javascript - CSS 不适用于首次点击

sql-server - 从字母数字字段中提取 6-8 位日期

javascript - 如果没有互联网连接使用 jquery 或 ajax 的对话框

bash - Perl Regex Query - 过滤文件中超过 18 个月的内容

android - 在 savedInstanceState 中存储日期的最佳方式是什么?

javascript - JavaScript Date 中的 T 分隔符是什么