营业时间判断?

5 个回答

`validateTime < endTime || validateTime > startTime`

`LocalTime`写成代码应该就类似如下：

``````LocalTime startTime = LocalTime.of(13, 0);
LocalTime endTime = LocalTime.of(3, 0);
LocalTime validateTime1 = LocalTime.of(16, 34);
LocalTime validateTime2 = LocalTime.of(3, 10);

Predicate<LocalTime> endBeforeStartPredicate = localTime -> localTime.isAfter(startTime) || localTime.isBefore(endTime);

System.out.println(endBeforeStartPredicate.test(validateTime1)); // true
System.out.println(endBeforeStartPredicate.test(validateTime2)); // false``````

``````LocalTime startTime = LocalTime.of(13, 0);
LocalTime endTime = LocalTime.of(3, 0);
LocalTime validateTime1 = LocalTime.of(16, 34);
LocalTime validateTime2 = LocalTime.of(3, 10);

BiFunction<LocalTime, LocalTime, Predicate<LocalTime>> biFunction = (start, end) ->
end.isAfter(start)
? localTime -> localTime.isAfter(start) && localTime.isBefore(end)
: localTime -> localTime.isAfter(start) || localTime.isBefore(end);

System.out.println(biFunction.apply(startTime, endTime).test(validateTime1)); // true
System.out.println(biFunction.apply(startTime, endTime).test(validateTime2)); // false

// startTime和endTime换一下位置，此时表示是当天的时间的比较，没有跨天
System.out.println(biFunction.apply(endTime, startTime).test(validateTime1)); // false
System.out.println(biFunction.apply(endTime, startTime).test(validateTime2)); // true
``````

`biFunction`这里的写法比较捡懒同时可以让代码放在一起，你可以选择整一个工具方法放着都行，感觉这样差不多叭~(￣(エ)￣)

`[0:00,3:00]``[13:00,24:00]`,这样不方便比较，其实再取一次反，表明不在营业时间的是`(3:00,13:00)`

`!(3:00<aTime<13:00)`

``````// 是按前才后开区间来判断的
static boolean inRange(LocalTime current, LocalTime begin, LocalTime end) {
var offset = begin.getHour();       // 用开始时间来找偏移量
var b = begin.minusHours(offset);   // 三个时间都减去偏移量
var e = end.minusHours(offset);
var v = current.minusHours(offset);
return !b.isAfter(v) && e.isAfter(v);
}``````

``````import java.time.LocalTime;

public class Problem {
public static void main(String[] args) {
var beginTime = LocalTime.of(13, 0);
var endTime = LocalTime.of(3, 0);
var v1 = LocalTime.of(16, 34);
var v2 = LocalTime.of(3, 10);
System.out.println("v1: " + inRange(v1, beginTime, endTime));  // true
System.out.println("v2: " + inRange(v2, beginTime, endTime));  // false
}

private static boolean inRange(LocalTime current, LocalTime begin, LocalTime end) {
var offset = begin.getHour();
var b = begin.minusHours(offset);
var e = end.minusHours(offset);
var v = current.minusHours(offset);
return !b.isAfter(v) && e.isAfter(v);
}
}``````

你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进