获取两个日期之间的日期列表未正确返回JS [英] Getting list of dates between two dates not returning correctly JS

查看:67
本文介绍了获取两个日期之间的日期列表未正确返回JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个开始日期和结束日期,我想生成这两个日期之间(包括)的日期列表。但我不知道为什么它不起作用...

I have a start date and an end date, and I want to generate a list of dates between (and including) these two dates. But I don't get why it isn't working...

我传入了几个JS日期对象,我已经显示了他们登录到控制台的内容下面

I pass in a couple of JS date objects, I've shown what they log to the console below

function dateList(dateStart, dateEnd) {
  console.log(dateStart);
  console.log(dateEnd);
  var dates = [];
  for ( i = dateStart; i <= dateEnd; i.setDate(i.getDate() + 1) ){
    dates.push(i);
  }
  return dates
}



Mon May 08 2017 00:00:00 GMT+0100 (BST)
Fri May 12 2017 00:00:00 GMT+0100 (BST)

返回的数组是

The array that is returned is

Array[5] 
0: Sat May 13 2017 00:00:00 GMT+0100 (BST)
1: Sat May 13 2017 00:00:00 GMT+0100 (BST)
2: Sat May 13 2017 00:00:00 GMT+0100 (BST)
3: Sat May 13 2017 00:00:00 GMT+0100 (BST)
4: Sat May 13 2017 00:00:00 GMT+0100 (BST)
length: 5
__proto__: Array[0]

...为什么??? ......

...Why???......

推荐答案

尝试添加新日期(i),而不仅仅是 i

Try to add new Date(i), instead of just i:

function dateList(dateStart, dateEnd) {
  var dates = [];
  for (i = dateStart; i <= dateEnd; i.setDate(i.getDate() + 1)){
    dates.push(new Date(i));
  }
  return dates;
}

console.log(dateList(new Date('2017-05-08'), new Date('2017-05-12')));

这篇关于获取两个日期之间的日期列表未正确返回JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆