Java LocalTime解析异常求助:时间判断逻辑失效
我帮你梳理下代码里的几个关键问题,顺便给你修正后的版本:
问题1:LocalTime解析"6:00"和"17:30"失败
你直接调用LocalTime.parse("6:00")时,默认会使用ISO_LOCAL_TIME格式(要求HH:mm:ss,比如06:00:00),但你的输入是6:00——既没有补零的小时位,也缺少秒数,所以会直接抛出解析异常。
解决方法:显式指定匹配的DateTimeFormatter,用"H:mm"格式(支持1-23的小时,不需要补零):
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("H:mm"); LocalTime calc = LocalTime.parse("6:00", timeFormatter); LocalTime calc2 = LocalTime.parse("17:30", timeFormatter);
问题2:时间比较逻辑完全错误
你现在用result.format(formatter).before(calc),这里result.format(formatter)返回的是String类型,调用的是字符串的before()方法——这是按字典序比较,不是时间顺序!比如字符串"10:00"和"6:00",字典序上"10:00"会被认为在"6:00"之前(因为'1'的ASCII码比'6'小),但实际时间上10:00是晚于6:00的,这会直接导致时段判断完全混乱。
正确的做法是直接用LocalTime自带的isBefore()和isAfter()方法比较时间对象:
boolean before = result.isBefore(calc); boolean after = result.isAfter(calc2);
额外隐藏坑:吞掉所有异常的catch块
你的catch (Exception e) {}什么都不做,会直接吞掉所有异常(比如解析失败、列表越界等),导致你根本不知道哪里出了问题。至少要打印异常信息,方便调试:
catch (Exception e) { System.err.println("处理第" + i + "条数据时出错:" + e.getMessage()); e.printStackTrace(); }
修正后的完整代码片段
// 遍历每个车牌 for (int i = 1, n = licenseplateList.size(); i < n; i++) { // 判断属于白天还是夜间时段 try { String time1Str = begintimeList.get(i); String time2Str = endingtimeList.get(i); // 定义时间格式化器,支持1-23的小时(比如6:00、17:30) DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H:mm"); LocalTime time1 = LocalTime.parse(time1Str, formatter); LocalTime time2 = LocalTime.parse(time2Str, formatter); LocalDate today = LocalDate.now(); LocalDateTime dateTime1 = LocalDateTime.of(today, time1); // 处理跨天的结束时间 LocalDateTime dateTime2 = time2.isAfter(time1) ? LocalDateTime.of(today, time2) : LocalDateTime.of(today.plusDays(1), time2); Duration duration = Duration.between(dateTime1, dateTime2); Duration halfDuration = duration.dividedBy(2); LocalTime result = LocalTime.from(halfDuration.addTo(time1)); System.out.println(result.format(formatter)); // 用正确的方式解析时段阈值 LocalTime calc = LocalTime.parse("6:00", formatter); LocalTime calc2 = LocalTime.parse("17:30", formatter); // 简化判断逻辑:早于6点或晚于17:30都算夜间 boolean isNight = result.isBefore(calc) || result.isAfter(calc2); if (isNight) { nachtMap.put(licenseplateList.get(i), kmperlineList.get(i)); } else { dagMap.put(licenseplateList.get(i), kmperlineList.get(i)); } } catch (Exception e) { // 打印异常,方便调试 System.err.println("处理第" + i + "条数据时出错:" + e.getMessage()); e.printStackTrace(); } }
内容的提问来源于stack exchange,提问作者wutBruh
相关产品推荐
相关产品推荐

