Skip to content

Instantly share code, notes, and snippets.

@BenArunski
Created December 18, 2015 21:29
Show Gist options
  • Save BenArunski/d3668d3322c3a49d0e9b to your computer and use it in GitHub Desktop.
Save BenArunski/d3668d3322c3a49d0e9b to your computer and use it in GitHub Desktop.
Utility class for detecting span overlaps
import java.util.Date;
public class TimeSpan {
private final Date start;
private final Date end;
public TimeSpan(Date start, Date end) {
if (start != null && end != null && end.before(start)) {
this.start = end;
this.end = start;
} else {
this.start = start;
this.end = end;
}
}
/**
* @param touchingIsOverlap if true, then 1/1-1/5 overlaps with 1/5-1/9.
*/
public boolean overlapsWith(TimeSpan timeSpan, boolean touchingIsOverlap) {
return isForever()
|| timeSpan.isForever()
|| isStartDateLessThanEndDate(start, timeSpan.end, touchingIsOverlap)
&& isStartDateLessThanEndDate(timeSpan.start, end, touchingIsOverlap);
}
private boolean isStartDateLessThanEndDate(Date start, Date end, boolean orEqualTo) {
return start == null
|| end == null
|| start.before(end)
|| orEqualTo && start.equals(end);
}
private boolean isForever() {
return start == null && end == null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment