我有两个小时的行程
10 PM - 02 AM
01 AM - 08 AM
我想检查它们中的任何一个是否与日期无关。
例如:第一个范围可能是8月1日和2日,而第二个范围可能是8月10日。
这就是我到目前为止
private Interval createInterval(final OpeningClosingTimesEntry entry) {
LocalDateTime openingHour = LocalDateTime.fromDateFields(entry.getOpenTime());
LocalDateTime closingHour = LocalDateTime.fromDateFields(entry.getCloseTime());
if(closingHour.isBefore(openingHour)){
closingHour = closingHour.plusDays(1);
}
return new Interval(openingHour.toDate().getTime(), closingHour.toDate().getTime());
}
private Interval adjustSecondIntervalDay(final Interval interval1, final Interval interval2){
if(interval1.getEnd().getDayOfYear() > interval2.getStart().getDayOfYear()){
DateTime start = interval2.getStart().plusDays(1);
DateTime end = interval2.getEnd().plusDays(1);
return new Interval(start, end);
}
return interval2;
}
这是使用Java 8正确执行操作的方法LocalTime
。您询问有关Joda Time的信息,但您说使用的是Java8。在大多数情况下,Joda Time建议切换到Java 8,这种情况也不例外。
由于您不在乎日期,而只是想知道时间是否重叠,因此您不应该使用诸如LocalDate
或LocalDateTime
,而是使用LocalTime
。
为了解决您的问题,我创建了isBetween
一种方法,该方法检查两个有序时间(一天中的某天)是否包含第三次时间,即使您传递到第二天也是如此。因此,例如21小时介于18小时和6小时之间。
然后,一旦有了该实用程序方法,只需检查两个范围中的至少一个是否包含另一个范围的边界即可。
我让您自行决定范围(例如1-2-2-3)。您拥有通用算法,其余部分则由您自己决定。
package so38810914;
import java.time.LocalTime;
import static java.util.Objects.*;
public class Question {
public static class LocalTimeRange {
private final LocalTime from;
private final LocalTime to;
public LocalTimeRange(LocalTime from, LocalTime to) {
requireNonNull(from, "from must not be null");
requireNonNull(to, "to must not be null");
this.from = from;
this.to = to;
}
public boolean overlaps(LocalTimeRange other) {
requireNonNull(other, "other must not be null");
return isBetween(other.from, this.from, this.to)
|| isBetween(other.to, this.from, this.to)
|| isBetween(this.from, other.from, other.to)
|| isBetween(this.to, other.from, other.to);
}
private static boolean isBetween(LocalTime t, LocalTime from, LocalTime to) {
if (from.isBefore(to)) { // same day
return from.isBefore(t) && t.isBefore(to);
} else { // spans to the next day.
return from.isBefore(t) || t.isBefore(to);
}
}
}
public static void main(String[] args) {
test( 0, 1, 2, 3, false);
test( 2, 3, 0, 1, false);
test( 0, 3, 1, 2, true);
test( 1, 2, 0, 3, true);
test( 0, 2, 1, 3, true);
test(12, 18, 15, 21, true);
test(18, 6, 21, 3, true);
test(21, 3, 0, 6, true);
test(21, 0, 3, 6, false);
}
private static void test(int from1, int to1, int from2, int to2, boolean overlap) {
LocalTimeRange range1 = new LocalTimeRange(LocalTime.of(from1, 0), LocalTime.of(to1, 0));
LocalTimeRange range2 = new LocalTimeRange(LocalTime.of(from2, 0), LocalTime.of(to2, 0));
boolean test = (range1.overlaps(range2)) == overlap;
System.out.printf("[%2d-%2d] - [%2d-%2d] -> %-5b: %s%n", from1, to1, from2, to2, overlap, test?"OK":"Not OK");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句