给定两个Date()
对象,其中一个小于另一个,我如何在这两个日期之间每天循环?
for(loopDate = startDate; loopDate < endDate; loopDate += 1)
{
}
这样的循环会起作用吗?但是我怎么才能给循环计数器增加一天呢?
谢谢!
发布于 2013-02-02 05:51:57
根据Tom Gullen的回答。
var start = new Date("02/05/2013");
var end = new Date("02/10/2013");
var loop = new Date(start);
while(loop <= end){
alert(loop);
var newDate = loop.setDate(loop.getDate() + 1);
loop = new Date(newDate);
}
发布于 2018-04-02 05:01:56
我想我找到了一个更简单的答案,如果你允许自己使用Moment.js
// cycle through last five days, today included
// you could also cycle through any dates you want, mostly for
// making this snippet not time aware
const currentMoment = moment().subtract(4, 'days');
const endMoment = moment().add(1, 'days');
while (currentMoment.isBefore(endMoment, 'day')) {
console.log(`Loop at ${currentMoment.format('YYYY-MM-DD')}`);
currentMoment.add(1, 'days');
}
<script src="https://cdn.jsdelivr.net/npm/moment@2/moment.min.js"></script>
发布于 2010-12-03 19:36:27
如果startDate和endDate确实是date对象,则可以将它们转换为自1970年1月1日午夜以来的毫秒数,如下所示:
var startTime = startDate.getTime(), endTime = endDate.getTime();
然后,您可以从一个循环到另一个循环,将loopTime递增86400000 (1000*60*60*24) -一天中的毫秒数:
for(loopTime = startTime; loopTime < endTime; loopTime += 86400000)
{
var loopDay=new Date(loopTime)
//use loopDay as you wish
}
https://stackoverflow.com/questions/4345045
复制相似问题