简体   繁体   中英

Comparing two Joda-Time DateTime objects

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?

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM