Comparing two Joda-Time DateTime objects

旧街凉风 提交于 2019-12-04 16:13:29

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/17172782/comparing-two-joda-time-datetime-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!