查找间隔之间的重叠

时间:2014-10-12 16:10:14

标签: java jodatime

假设我有2个joda-time LocalDate或2 DateTimeInterval。我想找一个间隔,即。 7月和8月存在于该区间内或与该区间重叠。如果是这样,我想找到重叠的间隔。 joda-time这可能吗?如果是,怎么样?

        LocalDate date = LocalDate.parse("2014-03-25");
        Period period = Period.months(6);
        DateTime start = date.toDateTimeAtStartOfDay();
        DateTime end = date.plus(period).toDateTimeAtStartOfDay();
        Interval interval = new Interval(start, end);
        // How do I find if this interval contains july and anugust?

1 个答案:

答案 0 :(得分:0)

这就是我得到理想结果的方式。

Interval interval = new Interval(start, end);
int startMonth = 7; int endMonth = 8;
DateTime month1 = start
        .withMonthOfYear(startMonth)
        .withDayOfMonth(1);
DateTime month2 = start
        .withMonthOfYear(endMonth + 1)
        .withDayOfMonth(1)
        .minusDays(1);
if (month1.compareTo(month2) > 0)
    month2.plusYears(1);
Interval season = new Interval(month1, month2);
if (season.overlaps(window)) {
    return  window.overlap(season);
}

重叠和重叠方法非常有用。