How to check a timeperiod is overlapping another time period in java

There is a simple solution, expressed here as a utility method:

public static boolean isOverlapping(Date start1, Date end1, Date start2, Date end2) {
    return start1.before(end2) && start2.before(end1);
}

This code requires there to be at least one millisecond to be shared between the two periods to return true.

If abutting time periods are considered to “overlap” (eg 10:00-10:30 and 10:30-11:00) the logic needs to be tweaked ever so slightly:

public static boolean isOverlapping(Date start1, Date end1, Date start2, Date end2) {
    return !start1.after(end2) && !start2.after(end1);
}

This logic more often comes up in database queries, but the same approach applies in any context.

Once you realise just how simple it is, you at first kick yourself, then you put it in the bank!

Leave a Comment