我有一些关于营业时间的数据,我正尝试使用 Joda-Time 表示。
一天中典型的营业时间是这样的:
9 点到 12 点,13 点到 20 点开放。
我在 Joda-Time 实体中表示它们的主要原因是为了验证它们:
- 检查营业时间是否有效(9 点在 12 点之前,等等)
- 检查开放区间是否重叠(“9-12 和 11-13”是非法的)
API 方面,Joda 时间 Interval类具有执行此验证所需的方法,但间隔是日期时间连续体中的成对瞬间。我想独立于绝对时间来表示它们,有点像两个 LocalTime 部分的间隔。这可能吗?
最佳答案
这是对自定义 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)); } }
关于java - 如何使用 Joda-Time 表达部分间隔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8818084/