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

前端 未结 5 1380
温柔的废话
温柔的废话 2020-11-27 06:14

How to check a time period is overlapping another time period in the same day.

For example,

  1. 7:00AM to 10:30AM is overlapping 10:00AM to 11:30AM
5条回答
  •  死守一世寂寞
    2020-11-27 06:50

    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!

提交回复
热议问题