Assume i have a start date and a end data as follows
end: "2021-10-22T06:00:00.000Z"
start: "2021-10-22T05:00:00.000Z"
I want to check if another given time range overlaps with the above time range in javascript. I tried using moment as follows.
return (
moment(timerange1.duration.end) <= moment(timerange2.duration.start) ||
moment(timerange1.duration.start) >= moment(timerange2.duration?.end)
);
But this does not produce the correct results. What would be the correct way to check if a certain time range overlaps with another time range using javascript?
Consider this:

In case A and C they do not overlap.
But what is true in B that isn't true in A or C?
Well, the start, or the end of the red one, is between the start and end of the blue one. That will always be true for overlapping timeperiods.
Example code:
if( (red.start > blue.start && red.start < blue.end) || (red.end > blue.start && red.end< blue.end) ) {
// do something
}
You can use the twix.js plugin for moment to handle the date ranges. In your code, you need to do something like that. This is sample code snippet you can modify it according to your need.
var t1 = {
start: "1982-01-25T09:30",
end: "1982-01-25T13:30",
};
var t2 = {
start: "1982-01-23T13:30",
end: "1982-01-25T12:30",
};
var t3 = {
start: "1982-01-24T13:30",
end: "1982-01-25T10:30",
};
var t1Range = moment(t1.start).twix(t1.end);
var t2Range = moment(t2.start).twix(t2.end);
var t3Range = moment(t3.start).twix(t3.end);
t1Range.overlaps(t2Range) || t1Range.overlaps(t3Range); //=> true
return (
(moment(timerange1.duration.start) >= moment(timerange2.duration.start) && moment(timerange1.duration.start) <= moment(timerange2.duration.end))
|| (moment(timerange1.duration.end) >= moment(timerange2.duration.start) && moment(timerange1.duration.end) <= moment(timerange2.duration.end))
|| (moment(timerange2.duration.start) >= moment(timerange1.duration.start) && moment(timerange2.duration.start) <= moment(timerange1.duration.end))
)
there are 3 different cases to consider as overlap
timerange1: |-----|
timerange2: |-----|
timerange1: |-----|
timerange2: |-----|
timerange1: |-----------|
timerange2: |-----|