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

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
  2. 7:00AM to 10:30AM is overlapping 8:00AM to 9:00AM
  3. 7:00AM to 10:30AM is overlapping 5:00AM to 8:00AM

3

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!

3

tl;dr

( startA.isBefore( stopB ) ) && ( stopA.isAfter( startB ) ) 

LocalTime

If you really want to work with a generic time-of-day without the context of a date and time zone, use the LocalTime class.

LocalTime startA = LocalTime.of( 7 , 0 );
LocalTime stopA = LocalTime.of( 10 , 30 );

LocalTime startB = LocalTime.of( 10 , 0 );
LocalTime stop2B = LocalTime.of( 11 , 30 );

Validate the data, being sure the ending is after the beginning (or equal). A briefer way of saying that is “beginning is not after ending”.

Boolean validA = ( ! startA.isAfter( stopA ) ) ;
Boolean validB = ( ! startB.isAfter( stop2B ) ) ;

Per this Answer by Meno Hochschild, using the Half-Open approach to defining a span of time where the beginning is inclusive while the ending is exclusive, we can use this logic:

(StartA < EndB) and (EndA > StartB)

Boolean overlaps = ( 
    ( startA.isBefore( stopB ) ) 
    && 
    ( stopA.isAfter( startB ) ) 
) ;

Note that LocalTime is constrained to a single generic 24-hour day. The times cannot go past midnight, cannot wrap around into another. There are no other days to consider. Validate your inputs to verify the beginning time comes before the end, or they are equal (if that suits your business rules).

if( stopA.isBefore( startA ) ) { … handle error  } 

if( stopB.isBefore( startB ) ) { … handle error  } 

ZonedDateTime

If you want to test actual moments on the timeline, you must adjust these time-of-day objects into the context of dates and a time zone. Apply a ZoneId to get a ZonedDateTime object.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
ZonedDateTime zdt = ZonedDateTime.of( today , startA , z);


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

If interval is opened (for example, some process is not finished yet) and end date might be null:

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

0

JOda Time has this functionality baked in. It’s very well-built and on JSR route to replace the broken Java Calendar API. You should probably considering using it.

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();
}

0

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật