Joda - How to compare two DateTime objects without ignoring TimeZones

Bitcoin Cash - ADA enthusiast picture Bitcoin Cash - ADA enthusiast · Aug 19, 2013 · Viewed 15.6k times · Source

I am having a hard time comparing two DateTime objects that are in different TimeZones.

What I already know:

1) I know that the "isBefore()" method does not take TimeZones into account. So, the "if" condition bellow is not true (even though I would like it to be true):

long aRandomTimeSinceTheEpoch = 1234567789L;

String TIMEZONE_SYDNEY_AUSTRALIA = "Australia/Sydney";
DateTimeZone sydneyTimeZone = DateTimeZone.forID(TIMEZONE_SYDNEY_AUSTRALIA);
Chronology chronologySydney = GJChronology.getInstance(sydneyTimeZone);

String TIMEZONE_NEWYORK = "America/New_York";
DateTimeZone newYorkTimeZone = DateTimeZone.forID(TIMEZONE_NEWYORK);
Chronology chronologyNewYork = GJChronology.getInstance(newYorkTimeZone);

DateTime sydneyDateTime = new DateTime(aRandomTimeSinceTheEpoch, chronologySydney);
DateTime newYorkDateTime = new DateTime(aRandomTimeSinceTheEpoch, chronologyNewYork);

if( newYorkDateTime.isBefore(sydneyDateTime) ){
    System.out.println("true");
}

2) Based on this answer (https://stackoverflow.com/a/8793980) it seems the correct way to do it is by Period instead, as Period is the right concept for what I am trying to do. However, that code throws an "UnsupportedOperationException - if the period contains years or months" exception sometimes (because I am dealing with dates that can be up to 2 years away from each other).

In short, all I want is an "isBefore()" method that takes TimeZones into account. (and that does not throw exceptions like the one above). How can I achieve this in Joda?

Answer

Matt Johnson-Pint picture Matt Johnson-Pint · Aug 19, 2013

What you're missing is that anytime you are measuring in seconds or milliseconds from the epoch - that is always in UTC.

So your sydneyDateTime and newYorkDateTime may have different zones, but since they are both originating from the same aRandomTimeSinceTheEpoch value, then they both occur at the same exact moment. Thus neither is before the other.

By analogy, it's like asking which is greater, 1 inch or 2.54 centimeters?

From your comments, it looks like you would like to compare the local times in each time zone, which you can do like this:

if( newYorkDateTime.toLocalDateTime().isBefore(sydneyDateTime.toLocalDateTime()) )

Note that if you are always starting from the same source instant, then this value will always be true. Just like 2.54 is always greater than 1.