简体   繁体   English

比较两个 ZonedDateTime 并忽略 Zone

[英]Compare two ZonedDateTime with ignoring the Zone

Compare two ZonedDateTime with ignoring the Zone:比较两个ZonedDateTime与忽略 Zone:

Example:例子:

2022-08-17 03:30:00+02 compare 2022-08-17 03:30:00+01 must give true 2022-08-17 03:30:00+02比较2022-08-17 03:30:00+01必须为true

I Have a stream that must compare each object with others using this Date:我有一个 stream 必须使用此日期将每个 object 与其他人进行比较:

Set<Tele> jPointsSet = jPoints.stream()
                .collect(Collectors.toCollection(() -> 
                                new TreeSet<>(Comparator.comparing(Tele::getDateM))));

the getDateM is ZonedDateTime so I would like when use Comparator.comparing(Tele::getDateM)) ignore the Zone getDateMZonedDateTime所以我想在使用Comparator.comparing(Tele::getDateM))时忽略 Zone

As @OH GOD SPIDERS said in the comments, you can extract LocalDateTime from a ZonedDateTime .正如@OH GOD SPIDERS在评论中所说,您可以从ZonedDateTime中提取LocalDateTime

Comparator.comparing(tele -> tele.getDateM().toLocalDateTime())

But be aware that if two LocalDateTime instances are equal, it doesn't necessarily mean that they're describing the same point in time.但请注意,如果两个LocalDateTime实例相等,并不一定意味着它们描述的是同一时间点。 In order to establish comparison based on a specific point in the global timeline, you need to use Instant .为了基于全局时间轴中的特定点建立比较,您需要使用Instant

Comparator.comparing(tele -> tele.getDateM().toInstant())

Sidenote: while dealing with a TreeSet , it's more handy to use NavigableSet interface as an abstract type.旁注:在处理TreeSet时,使用NavigableSet接口作为抽象类型更方便。 It gives you access to methods like pollFirst() , pollLast() , lower() , higher() , etc. which are not declared in the Set interface.它使您可以访问未在Set接口中声明的pollFirst()pollLast()lower() 、 Higher( higher()等方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM