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.
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.
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.
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.
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.
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);
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With