Check if two date periods overlap [duplicate]
- I have two date ranges, (start1,end1):::>>date1 && (start2,end2):::>>date2 .
I want to check if the two dates isOverLaped.
-
My flow chart I assume "<>=" operators is valid for comparing.
boolean isOverLaped(Date start1,Date end1,Date start2,Date end2) { if (start1>=end2 && end2>=start2 && start2>=end2) { return false; } else { return true; } }
- Any Suggestion will be appreciated.
You can use Joda-Time for this.
It provides the class Interval
which specifies a start and end instants and can check for overlaps with overlaps(Interval)
.
Something like
DateTime now = DateTime.now();
DateTime start1 = now;
DateTime end1 = now.plusMinutes(1);
DateTime start2 = now.plusSeconds(50);
DateTime end2 = now.plusMinutes(2);
Interval interval = new Interval( start1, end1 );
Interval interval2 = new Interval( start2, end2 );
System.out.println( interval.overlaps( interval2 ) );
prints
true
since the end of the first interval falls between the start and end of the second interval.
boolean overlap(Date start1, Date end1, Date start2, Date end2){
return start1.getTime() <= end2.getTime() && start2.getTime() <= end1.getTime();
}