tags:

views:

188

answers:

3

What's the best way to tell if one joda time DateTime object is within 4 hours of another if I don't know which object is earlier than the other?

The Joda Time Duration object seems to do this job well if I know that object A comes before object B, but since Duration is signed it doesn't seem to do what I want if I don't know the order.

Seems like there would be an easy way to do this, but I haven't found it yet.

A: 

You can use the compareTo() method on the two DateTime objects to tell which one is earlier and then use Duration to see if they are within 4 hours.

mR_fr0g
Thanks mR_fr0g, that one also works fine of course, but again, seems a bit clumsy.
Mike
A: 

Try the following:

if (Math.abs(new Duration(start, end).getStandardSeconds()) < 4 * 3600) {
  // blah blah blah
}
Paul Wagland
Yeah, that works fine of course, but it seems a bit clumsy
Mike
+4  A: 

Just use the Hours class for this:

Hours h = Hours.hoursBetween(date1, date2); 
int hours = h.getHours();
MicSim
Perfect! Exactly what I was looking for.
Mike
I noticed a little caveat on this. Scenario1: (time1 = 4:00:00) and (time2 = 8:00:00). This gives you 4 hours - no problem here. However in Scenario2: (time1 = 4:00:00) and (time2 = 8:30:00), you still get 4 hours when the time between is actually 4 hours and 30 minutes - which would be out of your timeframe. You could potentially get an extra (unwanted) hour.
Tony R
I noticed this question regarding elapsed time: http://stackoverflow.com/questions/2179644/how-to-calculate-elapsed-time-from-now-with-joda-time
Tony R