实际应用中,营业时间段问题
场景1:正常商户设置 2段 例如:09:00-12:00;13:30-20:00
场景2:外卖或夜场商户设置存在跨夜时间段 例如:20:00-3:00
思路:正常的处理方式是开始时间应当小于结束时间,startTime < endTime; 出现跨夜时,startTime > endTime,那么这种跨夜的场景应该怎么处理呢?
- 分解:startTime-24:00和00:00-endTime 2段
- 排序:对startTime排序
- 比较 :下一对时间startTime应大于上一对的endTime
代码示例:
public class TimeOver { public static boolean hasOverlap(List<TimeRange> timeRanges) { List<TimeRange> checkTimeRange = timeRanges.stream() .flatMap(timeRange -> { if (timeRange.start.isAfter(timeRange.end)) { // 特殊情况 00:00-03:00、19:00-00:00 if (timeRange.end.equals(LocalTime.MIDNIGHT)) { return Stream.of(new TimeRange(timeRange.start, LocalTime.MIDNIGHT)); }else { return Stream.of(new TimeRange(timeRange.start, LocalTime.MIDNIGHT), new TimeRange(LocalTime.MIDNIGHT, timeRange.end)); } } else { return Stream.of(timeRange); } }).sorted(Comparator.comparing(tr -> tr.start)).collect(Collectors.toList()); TimeRange lastRange = checkTimeRange.get(0); for (int i = 1; i < checkTimeRange.size(); i++) { TimeRange currentRange = checkTimeRange.get(i); if (currentRange.start.isBefore(lastRange.end) /*|| currentRange.start.isEqual(lastRange.end)*/) { return true; // 发现重叠 } lastRange = currentRange; } return false; // 没有发现重叠 } static class TimeRange { private LocalTime start; private LocalTime end; public TimeRange(String start, String end) { this.start = LocalTime.parse(start); this.end = LocalTime.parse(end); } public TimeRange(LocalTime start, LocalTime end) { this.start = start; this.end = end; } } // 示例使用 public static void main(String[] args) { List<TimeRange> timeRanges = Arrays.asList( new TimeRange("00:00", "11:00"), new TimeRange("13:00", "19:00"), new TimeRange("23:00", "00:00"), new TimeRange("23:59", "00:01") ); boolean hasOverlap = hasOverlap(timeRanges); System.out.println("Time ranges overlap: " + hasOverlap); } }