提问人:R Zav 提问时间:5/14/2023 最后编辑:AnonymousR Zav 更新时间:6/12/2023 访问量:158
无法从 TemporalAccessor:获取 LocalDateTime:尝试对流中的日期进行排序时
Unable to obtain LocalDateTime from TemporalAccessor: when trying to sort the date in the stream
问:
我想按日期(“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();
}
}
答:
0赞
WJS
6/12/2023
#1
您需要:
- 将格式化程序时间更改为 24 小时制。
HH
- use ,而不是 .
LocalTime
LocalDateTime
若要轻松显示值,可以在类中重写。这是一种可能的格式。toString()
@Override
public String toString() {
return String.format(
"PostX [id=%s, name=%s, score=%s, timePublication=%s]", id,
name, score, timePublication);
}
然后执行以下操作:
List<PostX> posts1 = posts.stream()
.sorted(Comparator.comparing(o->LocalTime.parse(o.timePublication, formatter)))
.limit(5).toList();
posts1.forEach(System.out::println);
指纹
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]
评论
LocalTime
Instant
SimpleDateFormat
Date
hh
HH
LocalDateTime
LocalDateTime
LocalTime