如何使用Joda-Time表达部分间隔?

时间:2012-01-11 10:57:34

标签: java jodatime

我有一些关于我试图用Joda-Time代表的开放时间的数据。

典型的开放时间如下:

从9到12,从13到20。

我在Joda-Time实体中表示它们的主要原因是验证它们:

  • 检查开放时间是否有效(9是在12之前等)
  • 检查没有开放区间重叠(“9-12和11-13”是非法的)

API方面,Joda-Time Interval类具有执行此验证所需的方法,但Intervals是日期 - 时间 - 连续体中的一对时刻。我想代表他们独立于绝对时间,有点像两个LocalTime部分的间隔。这可能吗?

1 个答案:

答案 0 :(得分:6)

这是对自定义TimeInterval的尝试(非常类似于Gray评论的解决方案):

import org.joda.time.*;

public class TimeInterval {
    private static final Instant CONSTANT = new Instant(0);
    private final LocalTime from;
    private final LocalTime to;

    public TimeInterval(LocalTime from, LocalTime to) {
        this.from = from;
        this.to = to;
    }

    public boolean isValid() {
        try { return toInterval() != null; } 
        catch (IllegalArgumentException e) { return false;}
    }

    public boolean overlapsWith(TimeInterval timeInterval) {
        return this.toInterval().overlaps(timeInterval.toInterval());
    }

    /**
     * @return this represented as a proper Interval
     * @throws IllegalArgumentException if invalid (to is before from)
     */
    private Interval toInterval() throws IllegalArgumentException {
        return new Interval(from.toDateTime(CONSTANT), to.toDateTime(CONSTANT));
    }
}
相关问题