ler - 1 year ago 50

Javascript Question

I have two ranges of dates. [2016-1-1, 2016-3-1] and [2016-2-21, 2016-10-1] and i want to get the number of weeks between those two ranges of dates useing Javascript or Jquery or any libraries.

what i mean by the number of weeks between thos two ranges if for example the first range is [2016-1-1, 2016-3-1] and the second is [2016-2-21, 2016-10-1] so there are one week between those two ranges that one week is the week from 2016-2-21 to 2016-3-1. i mean the Common

Answer

There's a library, moment.js, that will be a great help in doing this.

Sort the ranges by begin date. This makes it easier to detect the overlap. Then calculate the overlap and turn it into weeks.

```
var format = 'YYYY-MM-DD';
function intersectDateRanges(dates) {
if(dates.length == 0) return null;
if(dates.length == 1) return dates[0].slice(0);
dates = dates.map(function(v,i,a){
var start = moment(v[0],format).startOf('day');
var end = moment(v[1],format).endOf('day');
return [start,end];
});
dates.sort(function(a,b){
if(a[0].isBefore(b[0])) return -1;
if(a[0].isAfter(b[0])) return 1;
return 0;
});
var range = dates[0].slice(0);
for(var i = 1; i < dates.length; i++) {
if(dates[i][0].isAfter(range[1])) return null;
range[0] = dates[i][0];
if(dates[i][1].isBefore(range[1])) {
range[1] = dates[i][1];
}
}
return range;
}
function rangeToWeeks(range){
if(!range) return NaN;
return moment.duration(range[1] - range[0]).asWeeks();
}
var dates = [
['2016-1-1','2016-3-1'],
['2016-2-21','2016-10-1']
];
var weeksIntersect = rangeToWeeks(intersectDateRanges(dates));
```

Source (Stackoverflow)