基本上你需要检查你的startTime
and endTime
是倒置的(即如果endTime
是在之前startTime
)。如果是,那一定是“夜间”间隔,您应该将其视为相反的情况,然后反转结果。
public boolean isWithinInterval(LocalTime start, LocalTime end, LocalTime time) {
if (start.isAfter(end)) {
return !isWithinInterval(end, start, time);
}
// This assumes you want an inclusive start and an exclusive end point.
return start.compareTo(time) <= 0 &&
time.compareTo(end) < 0;
}
现在唯一的奇怪之处是,如图所示,开始时间通常是包含的,而结束时间是排除的 - 而如果我们反转结果(和参数),我们就会有一个包含的结束时间和一个排除的开始时间。因此,您可能想明确地处理这些情况:
public boolean isWithinInterval(LocalTime start, LocalTime end, LocalTime time) {
if (start.isAfter(end)) {
// Return true if the time is after (or at) start, *or* it's before end
return time.compareTo(start) >= 0 ||
time.compareTo(end) < 0;
} else {
return start.compareTo(time) <= 0 &&
time.compareTo(end) < 0;
}
}
(你如何选择你使用的目标和参数compareTo
当然,这取决于你。有多种方法可以有效地编写相同的代码。)
简短但完整的示例:
import org.joda.time.LocalTime;
public class Test {
public static void main(String[] args) {
LocalTime morning = new LocalTime(6, 0, 0);
LocalTime evening = new LocalTime(18, 0, 0);
LocalTime noon = new LocalTime(12, 0, 0);
LocalTime midnight = new LocalTime(0, 0, 0);
System.out.println(isWithinInterval(morning, evening, noon)); // true
System.out.println(
isWithinInterval(morning, evening, midnight)); // false
System.out.println(
isWithinInterval(evening, morning, noon)); // false
System.out.println(
isWithinInterval(evening, morning, midnight)); // true
}
public static boolean isWithinInterval(LocalTime start,
LocalTime end,
LocalTime time) {
if (start.isAfter(end)) {
// Return true if the time is after (or at) start,
// *or* it's before end
return time.compareTo(start) >= 0 ||
time.compareTo(end) < 0;
} else {
return start.compareTo(time) <= 0 &&
time.compareTo(end) < 0;
}
}
}