开发者

Compare right-unbounded time intervals with joda-lib

Is it possible to determine wether two rigth-unbounded intervals (intervals with one boundary at infinity) overlap or not?

I've tried this (and other similar variations):

Instant now = new In开发者_StackOverflowstant(new Date().getTime());
Interval i2 = new Interval(now, (ReadableInstant) null);
Interval i1 = new Interval(now, (ReadableInstant) null);
boolean overlapping = i2.overlaps(i1);

But according to the docs, using null as a second parameter means "now" instead of "infinity".

EDIT: I've found this answer in the mailing list, so it seems to be impossible with Joda. I am now looking for alternative implementations.


If both intervals start at t = -∞ , or if both intervals end at t = +∞, they will always overlap, regardless of the start date.

If interval A starts at t = -∞ and interval B ends at t = +∞, they overlap iff
A.start > B.start.


Hacky solution:

/**
 * Checks if two (optionally) unbounded intervals overlap each other.
 * @param aBeginn
 * @param aEnde
 * @param bBeginn
 * @param bEnde
 * @return
 */
public boolean checkIfOverlap(LocalDate aBeginn,LocalDate aEnde, LocalDate bBeginn,LocalDate bEnde){
    if(aBeginn == null){
        //set the date to the past if null
        aBeginn = LocalDate.now().minusYears(300);
    }
    if(aEnde == null){
        aEnde = LocalDate.now().plusYears(300);
    }
    if(bBeginn == null){
        bBeginn = LocalDate.now().minusYears(300);
    }
    if(bEnde == null){
        bEnde = LocalDate.now().plusYears(300);
    }

    if(aBeginn != null && aEnde != null && bBeginn != null && bEnde != null){
        Interval intervalA = new Interval(aBeginn.toDateTimeAtStartOfDay(),aEnde.toDateTimeAtStartOfDay());
        Interval intervalB = new Interval(bBeginn.toDateTimeAtStartOfDay(),bEnde.toDateTimeAtStartOfDay());
        if(intervalA.overlaps(intervalB)){
            return true;
        }
    } else{
        return false;
    }
    return false;
}


I'd recommend using a Range<DateTime> (from Guava), which should provide all the construction options and comparison functions you need.

Range<DateTime> r1= Range.atLeast(DateTime.now());
Range<DateTime> r2 = Range.atLeast(DateTime.now());
boolean overlap = r1.isConnected(r2) && !r1.intersection(r2).isEmpty();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜