14

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.

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.

Bruce Lowe
  • 6,063
  • 1
  • 36
  • 47
  • See similar Question: [Convert java.util.Date to what “java.time” type?](http://stackoverflow.com/q/36639154/642706) – Basil Bourque Mar 26 '17 at 02:06

3 Answers3

20

The equivalent of Date in the new API is 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);
assylias
  • 321,522
  • 82
  • 660
  • 783
  • This looks exactly like what I need. I didnt realise the Instant was closer to Date than a LocalDateTime is. – Bruce Lowe Oct 16 '14 at 10:17
  • 1
    @BruceLowe a LocalDateTime does not represent an instant because today at 5pm could be many different instants depending on your timezone. Both Date and Instant represent a number of milliseconds since the epoch. – assylias Oct 16 '14 at 10:34
1

You can convert LocalDateTime to Date by the help of Instant

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");
}
akash
  • 22,664
  • 11
  • 59
  • 87
  • The first three lines can be simplified to Date ``dateFromLocalDT = Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant());``. – Sven Döring Jun 29 '23 at 06:41
1

Just convert your java.util.Date to LocalDateTime.

aMonthAgo.compareTo( LocalDateTime.ofInstant(dbDate.toInstant(), ZoneId.systemDefault()));
DaafVader
  • 1,735
  • 1
  • 14
  • 14