Unable to obtain LocalDateTime from TemporalAccessor: when trying to sort the date in the stream

400 Views Asked by At

I want to sort the posts by date("hh:mm:ss"). but I get a mistake. Can you tell me what I did wrong?

java.time.format.DateTimeParseException: Text '12:55:36' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {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();
    }
}
1

There are 1 best solutions below

0
WJS On

You need to:

  • change your formatter hours to HH for 24 hour clock.
  • use LocalTime, not LocalDateTime.

To easily display the values, you can override toString() in your class. Here is one possible format.

 @Override
 public String toString() {
     return String.format(
             "PostX [id=%s, name=%s, score=%s, timePublication=%s]", id,
             name, score, timePublication);
 }

Then do the following:


List<PostX> posts1 = posts.stream()
                .sorted(Comparator.comparing(o->LocalTime.parse(o.timePublication, formatter)))
                .limit(5).toList();

posts1.forEach(System.out::println);

prints

PostX [id=5, name=post5, score=10, timePublication=01:50:36]
PostX [id=2, name=post2, score=0, timePublication=12:55:36]
PostX [id=3, name=post3, score=100, timePublication=19:55:36]
PostX [id=7, name=post7, score=4, timePublication=20:15:36]
PostX [id=1, name=post1, score=10, timePublication=20:55:36]