4

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.

emmby
  • 99,783
  • 65
  • 191
  • 249

3 Answers3

9

Just use the Hours class for this:

Hours h = Hours.hoursBetween(date1, date2); 
int hours = h.getHours();
MicSim
  • 26,265
  • 16
  • 90
  • 133
  • Perfect! Exactly what I was looking for. – emmby Sep 28 '09 at 22:24
  • 1
    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 Feb 26 '10 at 21:22
  • I noticed this question regarding elapsed time: http://stackoverflow.com/questions/2179644/how-to-calculate-elapsed-time-from-now-with-joda-time – Tony R Feb 26 '10 at 21:27
  • Is there a way to find out if the current hour of the day falls between two given hours of the day? For e.g. 6 falls between 21 and 9, so the function should return true. – Andy Dufresne Jul 17 '14 at 06:05
  • For sure there is. You could ask this as a separate question on SO along with what you have tried. – MicSim Jul 17 '14 at 07:31
0

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
  • 8,462
  • 7
  • 39
  • 54
0

Try the following:

if (Math.abs(new Duration(start, end).getStandardSeconds()) < 4 * 3600) {
  // blah blah blah
}
Paul Wagland
  • 27,756
  • 10
  • 52
  • 74