Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two dates using Joda time

I want to compare two dates, however I'm running into trouble. 1 date is created from a java.util.date object and the other is manually crafted. The following code is an example:

Date ds = new Date(); DateTime d = new DateTime(ds);  DateTime e = new DateTime(2012,12,07, 0, 0); System.out.println(d.isEqual(e)); 

However the test turns out false. I am guessing that it is because of the time. How can I check if these two dates are equal to each other (I mean the Year, month, date are identical)?

like image 596
Marc Rasmussen Avatar asked Dec 07 '12 13:12

Marc Rasmussen


People also ask

How can I compare two dates?

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.

Is Joda-time deprecated?

So the short answer to your question is: YES (deprecated).

What is the replacement of Joda-time?

time (JSR-310) which is a core part of the JDK which replaces joda library project.


2 Answers

System.out.println(d.toDateMidnight().isEqual(e.toDateMidnight())); 

or

System.out.println(d.withTimeAtStartOfDay().isEqual(e.withTimeAtStartOfDay())); 
like image 60
JB Nizet Avatar answered Oct 02 '22 11:10

JB Nizet


You should use toLocalDate():

date1.toLocalDate().isEqual(date2.toLocalDate()) 

This will get rid of the Time part of the DateTime.

There is another approach, but it does not account for the case where the two dates have a different timezone, so it's less reliable:

date1.withTimeAtStartOfDay().isEqual(date2.withTimeAtStartOfDay()) 
like image 40
Stan Avatar answered Oct 02 '22 10:10

Stan