Hienz
Hienz

Reputation: 718

Check if two date intervals have common times

Let's say, I have two date intervals, 09:00 - 16:00 and 13:00 - 18:00. I want to check, if the two intervals have any common time. The above example has, the 13:00-16:00.

Data structure of intervals is something like this:

{
    "begin": 324872,
    "end": 532424
}

So there is a shift, and I want to check if a person was working on that shift, or not:

if(shift.Begin <= personWorkBegin && shift.End >= personWorkBegin) 

But this is not a solution, since it has to be inside that interval, and I just want to check common parts.

Upvotes: 1

Views: 190

Answers (2)

Nanna
Nanna

Reputation: 575

Maybe not the most neat solution, but should do the trick:

if (personWorkBegin >= shift.Begin && personWorkBegin <= shift.End ||
    personWorkEnd >= shift.Begin && personWorkEnd <= shift.End ||
    personWorkBegin <= shift.Begin && personWorkEnd >= shift.End) 

EDIT: The fourth check was redundant, as pointed out by canton7, and has been removed.

Upvotes: 2

Tom Dee
Tom Dee

Reputation: 2674

You can just do the end of the first interval subtract the start of the second interval. If it is less than 0 then there is no overlap. If is greater than 0 then the overlap interval will be the end of the first interval add the difference.

Upvotes: 0

Related Questions