Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two Joda-Time DateTime objects

Tags:

java

jodatime

I am dealing with something very similar to what has been asked here - compare Joda-Time time zones but it does not seem to work for me.

Here's a piece of code which I am testing Joda-Time DateTime with -

 DateTime estDT = new DateTime(DateTimeZone.forID("America/Puerto_Rico")).withMillisOfSecond(0);   DateTime londonDT = new DateTime(DateTimeZone.forID("Europe/London")).withMillisOfSecond(0);      System.out.println("Comparison " + londonDT.isBefore(estDT));      System.out.println("Comparison " + londonDT.isAfter(estDT));  

Interestingly enough, I get 'false' from both the sysout statements above. Can anyone please explain what will be the right way of doing this comparison?

like image 404
FSP Avatar asked Jun 18 '13 15:06

FSP


People also ask

How to check if two date objects are equal 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.

Can you compare DateTime?

The DateTime. Compare() method in C# is used for comparison of two DateTime instances. It returns an integer value, <0 − If date1 is earlier than date2.


2 Answers

isAfter and isBefore methods compare dates by millis (ignoring time zone).

In your example, the dates have equal millis.

System.out.println(londonDT.getMillis() == estDT.getMillis());   

will print true.

Expressions

londonDT.isBefore(estDT)  londonDT.isAfter(estDT) 

are equal to

londonDT.getMillis() < estDT.getMillis()   londonDT.getMillis() > estDT.getMillis() 
like image 151
Ilya Avatar answered Sep 21 '22 09:09

Ilya


You're creating two DateTime instances probably representing the same instant in time, but with different time zones. Neither is before or after the other.

The time zone just affects how the date/time methods like getHourOfDay() convert the instant in time.

like image 36
Andy Thomas Avatar answered Sep 20 '22 09:09

Andy Thomas