无法从 TemporalAccessor 获取 LocalDateTime:尝试对流中的日期进行排序时

问题描述 投票:0回答:0

我想按日期(“hh:mm:ss”)对帖子进行排序。但我弄错了。你能告诉我我做错了什么吗?

java.time.format.DateTimeParseException: 文本 '12:55:36' 不能 已解析:无法从 TemporalAccessor 获取 LocalDateTime: {HourOfAmPm=0,MinuteOfHour=55,SecondOfMinute=36,MicroOfSecond=0, MilliOfSecond=0, NanoOfSecond=0}

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 -> LocalDateTime.parse(o.timePublication, formatter))).limit(5).toList();
    }
}
java java-stream java-time datetime-parsing
© www.soinside.com 2019 - 2024. All rights reserved.