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

前端 未结 5 1397
温柔的废话
温柔的废话 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:44

    EDIT:

    Here is the working method:

    public boolean isOverlapping(Date start1, Date end1, Date start2, Date end2) {
        return start1.compareTo(end2) <= 0 && end1.compareTo(start2) >= 0;
    }
    

    And here is proof for everyone to try it:

    @Test
    public void isOverlapping_base() {
        Assert.assertTrue(isOverlapping(getDate(2014, 1, 1),
                getDate(2014, 3, 31), getDate(2014, 1, 2),
                getDate(2014, 4, 1)));
        
        Assert.assertTrue(isOverlapping(getDate(2014, 1, 2),
                getDate(2014, 4, 1), getDate(2014, 1, 1),
                getDate(2014, 3, 31)));
        
        Assert.assertTrue(isOverlapping(getDate(2014, 1, 1),
                getDate(2014, 4, 1), getDate(2014, 1, 2),
                getDate(2014, 3, 31)));
        
        Assert.assertTrue(isOverlapping(getDate(2014, 1, 2),
                getDate(2014, 3, 31), getDate(2014, 1, 1),
                getDate(2014, 4, 1)));
        
        Assert.assertFalse(isOverlapping(getDate(2014, 1, 1),
                getDate(2014, 1, 31), getDate(2014, 3, 1),
                getDate(2014, 3, 31)));
        
        Assert.assertFalse(isOverlapping(getDate(2014, 3, 1),
                getDate(2014, 3, 31), getDate(2014, 1, 1),
                getDate(2014, 1, 31)));
    }
    
    Date getDate(int year, int month, int date) {
        Calendar working = Calendar.getInstance();
        working.set(year, month - 1, date, 0, 0, 0); 
        working.set(Calendar.MILLISECOND, 0);
        return working.getTime();
    }
    

提交回复
热议问题