3

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

3 Answers3

6

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.

ozOli
  • 1,414
  • 1
  • 18
  • 26
Tommi Gustafsson
  • 1,860
  • 4
  • 17
  • 20
  • Thanks, this still works as of moment v.2.9.0, but you need to switch the order of args in your incrementer (that way is deprecated). It should now be `date.add(1, 'days')` – Aaron Krauss Mar 20 '15 at 18:46
1

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());
}
0
   var one_day=1000*60*60*24;

    // Convert both dates to milliseconds
   var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

   enter code here

  -- Calculate the difference in milliseconds
   var difference_ms = date2_ms - date1_ms;
   var diff=Math.round(difference_ms/one_day); 

    for(var i=0;i<diff;i++)
     {
       // here your calculatiuon
     }
Lineesh
  • 106
  • 1
  • 1
  • 6