Check if more than two date ranges overlap
Here is refined version of what Paul posted:
- Added filter and null check to allow any number of entries
- Changed the logic so that it can be applied on an array. Eg: [{"from": value, "to": value}]
- Adjusted overlap check to allow times having end and start as same
Script:
function dateRangeOverlaps(a_start, a_end, b_start, b_end) {
if (a_start < b_start && b_start < a_end) return true; // b starts in a
if (a_start < b_end && b_end < a_end) return true; // b ends in a
if (b_start < a_start && a_end < b_end) return true; // a in b
return false;
}
function multipleDateRangeOverlaps(timeEntries) {
let i = 0, j = 0;
let timeIntervals = timeEntries.filter(entry => entry.from != null && entry.to != null && entry.from.length === 8 && entry.to.length === 8);
if (timeIntervals != null && timeIntervals.length > 1)
for (i = 0; i < timeIntervals.length - 1; i += 1) {
for (j = i + 1; j < timeIntervals.length; j += 1) {
if (
dateRangeOverlaps(
timeIntervals[i].from.getTime(), timeIntervals[i].to.getTime(),
timeIntervals[j].from.getTime(), timeIntervals[j].to.getTime()
)
) return true;
}
}
return false;
}
//storing existing dates for comparison
public multipleExistingDates=[
{startDate:'02/03/2020 05:00:00',endDate:'02/03/2020 05:30:00'},
{startDate:02/04/2020 05:00:00'',endDate:'02/05/2020 05:00:00'},]
/The date to be compared with existing dates to check if the new date is overlapping with existing dates/
public checkOverlappingDsates(startDate:Date, endDate:Date):boolean{
return this.multipleExistingDates.some((elem)=>{
return( !((moment(endDate).diff(moment(elem.startDate))) < 0 ||
(moment(startDate).diff(moment(elem.endDate))) > 0;})
Note: If the date is overlapping, the function return true else false. Also , you would need to install moment for date comparison.
You can use nested for
loops with arguments
function dateRangeOverlaps(a_start, a_end, b_start, b_end) {
if (a_start <= b_start && b_start <= a_end) return true; // b starts in a
if (a_start <= b_end && b_end <= a_end) return true; // b ends in a
if (b_start < a_start && a_end < b_end) return true; // a in b
return false;
}
function multipleDateRangeOverlaps() {
var i, j;
if (arguments.length % 2 !== 0)
throw new TypeError('Arguments length must be a multiple of 2');
for (i = 0; i < arguments.length - 2; i += 2) {
for (j = i + 2; j < arguments.length; j += 2) {
if (
dateRangeOverlaps(
arguments[i], arguments[i+1],
arguments[j], arguments[j+1]
)
) return true;
}
}
return false;
}
Below code comes from my project, maybe it will help you:
function dateRangeOverlaps(startDateA, endDateA, startDateB, endDateB) {
if ((endDateA < startDateB) || (startDateA > endDateB)) {
return null
}
var obj = {};
obj.startDate = startDateA <= startDateB ? startDateB : startDateA;
obj.endDate = endDateA <= endDateB ? endDateA : endDateB;
return obj;
}