Detect if two tasks collide in java

58 views Asked by At

I have the following case: Two tasks, A and B, each with a given time window that specifies the earliest time the task can start, called earliestStart and the latest time the task can end, called latestEnd. In addition, the tasks have a given duration, that is equal or less than latestEnd - earliestStart for that specific task. E.g task A has to be performed within 08:00-10:00 and the duration is 1 hour, while task B has to be performed within 08:50-09:55, and the duration is 1 hour. How can I check this easily in java, is this correct? (to prove that they are not overlapping):

taskA.earliestStart + taskA.duration < taskB.latestEnd - taskB.duration 
|| taskB.earliestStart + taskB.duration < taskA.latestEnd - taskA.duration
1

There are 1 answers

0
Basil Bourque On

Use LocalTime to represent a time-of-day without date and without time zone.

LocalTime aStart = LocalTime.of( 8 , 0 ) ;
Duration aDuration = Duration.ofHours( 1 ) ;
LocalTime aStop = aStart.plus( aDuration ) ;

Compare using isBefore, isAfter, and equals methods.