Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Date and a LocalDateTime in Java 8

Tags:

java

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.

like image 495
Bruce Lowe Avatar asked Oct 16 '14 10:10

Bruce Lowe


People also ask

How does LocalDateTime compare dates?

LocalDate compareTo() Method The method compareTo() compares two instances for the date-based values (day, month, year) and returns an integer value based on the comparison. 0 (Zero) if both the dates represent the same date in calendar. Positive integer if given date is latter than the otherDate.

What is the difference between date and LocalDateTime in Java?

LocalDate is the date the calendar on the wall says. java. util. Date is not a date, it's an instant, and actually represents a millisecond offset from Unix epoch.

Can we compare date and LocalDate in Java?

LocalDateTime instances contain the date as well as the time component. Similarly to LocalDate, we're comparing two LocalDateTime instances with the methods isAfter(), isBefore() and isEqual(). Additionally, equals() and compareTo() can be used in a similar fashion as described for LocalDate.

How can I compare two date and time in Java?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.


2 Answers

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);
like image 159
assylias Avatar answered Sep 18 '22 18:09

assylias


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");
}
like image 37
akash Avatar answered Sep 19 '22 18:09

akash