I have the following code to create all possible intervals between two dates:
JavaScript
x
10
10
1
var minStart = new Date(2019, 10, 1);
2
var maxStart = new Date(2019, 10, 3);
3
var minStop = new Date(2019, 10, 20);
4
var maxStop = new Date(2019, 10, 22);
5
6
for (var i = minStart; i <= maxStart; i.setDate(i.getDate() + 1)) {
7
for (var v = minStop; v <= maxStop; v.setDate(v.getDate() + 1)) {
8
console.log(moment(i).format('DD/MM') + ' - ' + moment(v).format('DD/MM'));
9
}
10
}
I am expecting to get the following result:
JavaScript
1
10
10
1
01/11 - 20/11
2
01/11 - 21/11
3
01/11 - 22/11
4
02/11 - 20/11
5
02/11 - 21/11
6
02/11 - 22/11
7
03/11 - 20/11
8
03/11 - 21/11
9
03/11 - 22/11
10
but I am getting only:
JavaScript
1
4
1
>01/11 - 20/11
2
>01/11 - 21/11
3
>01/11 - 22/11
4
I debugged the code by putting more console.log()
outputs and it turns out, that the inner loop is run only once. Any idea why this is happening?
Here is a quick JSFiddle (without the moment
library that I am using only for formatting).
Advertisement
Answer
The problem is that you’re mutating the objects, at the end of the first outer loop, minStop
will have the same date as maxStop
. To address that, use something like this: var v = new Date(minStop)