按时分秒排序PostX列表时触发DateTimeParseException问题排查
问题原因分析
- 日期时间类型误用:你用
LocalDateTime解析仅含时分秒的字符串,但LocalDateTime需要完整的日期+时间信息,输入只有时间部分,无法生成包含日期的LocalDateTime对象,这是抛出异常的核心原因。 - 格式符错误:你使用的
hh:mm:ss中,hh是12小时制小时格式(范围1-12),但输入里有20:55:36、23:55:36这类24小时制时间,解析时会出现格式不匹配,即便像12:55:36这类符合12小时制的字符串,也会因缺少日期信息无法生成LocalDateTime。
修复方案
将解析目标换成仅处理时间的LocalTime,同时把格式符改为HH:mm:ss(24小时制小时格式),修改后的代码如下:
class PostX { int id; String name; int score; String timePublication; public PostX(int id, String name, int score, String timePublication) { this.id = id; this.name = name; this.score = score; this.timePublication = timePublication; } public static void main(String[] args) { List<PostX> posts = List.of( new PostX(1,"post1", 10, "20:55:36"), new PostX(2,"post2", 0, "12:55:36"), new PostX(3,"post3", 100, "19:55:36"), new PostX(4,"post4", 1000, "23:55:36"), new PostX(5,"post5", 10, "01:50:36"), new PostX(6,"post6", 3, "20:55:36"), new PostX(7,"post7", 4, "20:15:36") ); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); List<PostX> posts1 = posts.stream() .sorted(Comparator.comparing(o -> LocalTime.parse(o.timePublication, formatter))) .limit(5) .toList(); // 验证排序结果 posts1.forEach(post -> System.out.println(post.id + " " + post.timePublication)); } }
额外说明
LocalTime专门用于处理仅含时分秒的时间数据,完全匹配你的输入场景。HH对应24小时制小时(0-23),能正确解析所有给定的时间字符串;而hh仅适用于12小时制(1-12),通常还需配合a(上午/下午标识)使用。
内容的提问来源于stack exchange,提问作者R Zav
相关产品推荐
相关产品推荐

