比较 Java 8 中的日期和本地日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26401524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:26:01  来源:igfitidea点击:

Comparing Date and a LocalDateTime in Java 8

java

提问by Bruce Lowe

I am using Java 8 and querying a Mongo database which is returning a java.util.Date object. I now want to check that the item is within the last 30 days. I'm attempting to use the new time API to make the code more update to date.

我正在使用 Java 8 并查询返回 java.util.Date 对象的 Mongo 数据库。我现在想检查该项目是否在过去 30 天内。我正在尝试使用新的时间 API 使代码更新得更多。

So I've written this code:

所以我写了这段代码:

java.time.LocalDateTime aMonthAgo = LocalDateTime.now().minusDays(30)

and I have a

我有一个

java.util.Date dbDate = item.get("t")

How would I compare these 2?

我如何比较这两个?

I'm sure I could just work with completely Dates/Calendars to do the job, or introduce joda-time. But I'd prefer to go with a nicer Java 8 solution.

我确信我可以完全使用日期/日历来完成这项工作,或者引入 joda-time。但我更喜欢使用更好的 Java 8 解决方案。

采纳答案by assylias

The equivalent of Date in the new API is Instant:

新 API 中 Date 的等价物是 Instant:

Instant dbInstant = dbDate.toInstant();

You can then compare that instant with another instant:

然后,您可以将该瞬间与另一个瞬间进行比较:

Instant aMonthAgo = ZonedDateTime.now().minusDays(30).toInstant();
boolean withinLast30Days = dbInstant.isAfter(aMonthAgo);

回答by CoderCroc

You can convert LocalDateTimeto Dateby the help of Instant

您可以 通过以下方式转换LocalDateTimeDateInstant

Date currentDate=new Date();
LocalDateTime localDateTime = LocalDateTime.ofInstant(currentDate.toInstant(), ZoneId.systemDefault());
Date dateFromLocalDT = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

if(dateFromLocalDT.compareTo(yourDate)==0){
    System.out.println("SAME");
}

回答by DaafVader

Just convert your java.util.Date to LocalDateTime.

只需将您的 java.util.Date 转换为 LocalDateTime。

aMonthAgo.compareTo( LocalDateTime.ofInstant(dbDate.toInstant(), ZoneId.systemDefault()));