Reputation: 1167
Scenario 1
Time range 1 : 2016-12-06 11:00 to 2016-12-06 12:00
Time range 2 : 2016-12-06 10:00 to 2016-12-06 13:00
time range 1 is completely conflict with time range 2 and vice versa
Scenario 2
Time range 1 : 2016-12-06 11:00 to 2016-12-06 12:00
Time range 2 : 2016-12-06 11:00 to 2016-12-06 14:00
time range 1 is partial conflict with time range 2 and vice versa
Scenario 3
Time range 1 : 2016-12-06 11:00 to 2016-12-06 12:00
Time range 2 : 2016-12-06 09:00 to 2016-12-06 12:00
time range 1 is partial conflict with time range 2 and vice versa
How to accomplish above scenario using momentjs? I tried the isBetween
function but couldn't get it work.
Upvotes: 7
Views: 5114
Reputation: 4799
I think moment-range is what you are looking for. Use its overlaps
and contains
function to make it. You can link to moment-range from the cdnjs servers.
var date1 = [moment("2016-12-06 11:00"), moment("2016-12-06 12:00")];
var date2 = [moment("2016-12-06 10:00"), moment("2016-12-06 13:00")];
var range = moment.range(date1);
var range2 = moment.range(date2);
// has overlapping
if(range.overlaps(range2)) {
if((range2.contains(range, true) || range.contains(range2, true)) && !date1[0].isSame(date2[0]))
alert("time range 1 is completely conflict with time range 2 and vice versa");
else
alert("time range 1 is partially conflict with time range 2 and vice versa");
}
Upvotes: 10
Reputation: 261
You can use isBetween and test the scenario by calculating the weight of the conflict.
function testDate(d1, d2) {
// d1 and d2 in array format
// [moment from, moment to]
var count = 0;
for (var i = 0, t; t = d1[i]; i++) {
// use isBetween exclusion
if (t.isBetween(d2[0], d2[1], null, '()')) {
count++;
}
}
for (var i = 0, t; t = d2[i]; i++) {
// use isBetween exclusion
if (t.isBetween(d1[0], d1[1], null, '()')) {
count++;
}
}
if (count > 1) {
return console.log('completely conflict');
}
if (count > 0) {
return console.log('partial conflict');
}
return console.log('something else');
}
var time1 = [moment('2016-12-06 11:00'), moment('2016-12-06 12:00')];
var time2 = [moment('2016-12-06 10:00'), moment('2016-12-06 13:00')];
var time3 = [moment('2016-12-06 11:00'), moment('2016-12-06 12:00')];
var time4 = [moment('2016-12-06 11:00'), moment('2016-12-06 14:00')];
var time5 = [moment('2016-12-06 11:00'), moment('2016-12-06 12:00')];
var time6 = [moment('2016-12-06 09:00'), moment('2016-12-06 12:00')];
testDate(time1, time2); // completely conflict
testDate(time3, time4); // partial conflict
testDate(time5, time6); // partial conflict
Upvotes: 0