[英]How to loop between dates that are in dmy format
这是我的两个约会
var startdate = '11-12-2016';
var stopdate = '13-12-2016';
我想在这两个日期之间循环。 所以,我确实是这样
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
while(startMedicine <= stopMedicine){
console.log(startdate)
}
但是我正在浏览器中运行无限循环。
我怎样才能做到这一点。
注意 :
我不想为此使用jQuery。
如果开始日期和结束日期相同,则应仅循环一次,并且输入日期将始终为d / m / y格式。 我的代码有什么错误? 请帮助
更新:
我误认为日期格式,我的日期格式是dmy。 我该怎么做一个..
使用getDate
每次迭代将日期递增一天
startdateArr = startdate.split('-');
stopdateArr = stopdate.split('-');
var startMedicine = new Date(startdateArr[2],startdateArr[1]-1,startdateArr[0]);
var stopMedicine = new Date(stopdateArr[2],stopdateArr[1]-1,stopdateArr[0]);
// thanks RobG for correcting on month index
while(startMedicine <= stopMedicine){
var v = startMedicine.getDate() + '-' + (startMedicine.getMonth() + 1) + '-' + startMedicine.getFullYear();
console.log(v);
startMedicine.setDate(startMedicine.getDate()+1);
}
在js月中,索引从0开始,因此nov为12月10日。 是11,就像这样,这就是为什么我使用getMonth() + 1
主要问题是您没有增加约会时间。
这是解决方案
var startdate = '11/12/2016';
var stopdate = '11/13/2016';
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
var currentMedicine = startMedicine;
var dayCount = 0;
while(currentMedicine < stopMedicine){
currentMedicine.setDate(startMedicine.getDate() + dayCount);
// You can replace '/' to '-' this if you want to have dd-mm-yyyy instead of dd/mm/yyy
var currentDate = currentMedicine.getDate() + '/' + (currentMedicine.getMonth() + 1) + '/' + currentMedicine.getFullYear(); // in dd/mm/yyyy format
console.log(currentDate);
dayCount++;
}
您可以利用矩js和矩js持续时间。 它仅用于持续时间。 这非常容易,并且意味着相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.