I am new to JavaScript and got stuck while iterating through date between given range in javascript. Please help me to solve this issue. I have 2 dates one is start date and other is end date. Loop should iterate from start date to end date. for each iteration start date should increment by one day. Thanks in Advance
You should use moment.js and then use
moment().add('days', 1);
The whole code would look like this:
let startDate = moment("2017-10-21");
let endDate = moment().add(-1, 'days'); // for yesterday
for (let date = moment(startDate); date.diff(endDate) < 0; date.add(1, 'days')) {
}
I hope I got it correctly.
You can use the trick with Date.setDate() method: it changes the day of month, but if you try to set a day out of month's range (1-30/31) it tries to change the whole date accordingly.
var startDate = new Date(), // Current moment
endDate = new Date(startDate.getTime() + 50*24*60*60*1000), // Current moment + 50 days
iDate = new Date(startDate); // Date object to be used as iterator
while (iDate <= endDate) {
console.log(iDate.toString());
iDate.setDate(iDate.getDate() + 1); // Switch to next day
}
Works fine with "for" too:
var startDate = new Date(),
endDate = new Date(startDate.getTime() + 50*24*60*60*1000);
for (var iDate = new Date(startDate); iDate < endDate; iDate.setDate(iDate.getDate() + 1)) {
console.log(iDate.toString());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With