Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.max(...) for JodaTime

Tags:

java

jodatime

I have two JodaTime objects and I wanted a method like so

// Return the latest of the two DateTimes
DateTime latest(DateTime a, DateTime b)

But I can't find such a thing. I could easily write it, but I'm sure JodaTime would have it somewhere.

like image 666
bramp Avatar asked May 11 '14 22:05

bramp


2 Answers

As Jack pointed out, DateTime implements Comparable. If you are using Guava, the maximum of two dates (let's say a and b) can be determined by the following shorthand:

Ordering.natural().max(a, b);
like image 177
W. Wisse Avatar answered Oct 05 '22 22:10

W. Wisse


DateTime implements Comparable so you don't need to roll you own other than doing:

DateTime latest(DateTime a, DateTime b)
{
  return a.compareTo(b) > 0 ? a : b;
}

or by using JodaTime API directly (which takes into account Chronology unlike compareTo):

DateTime latest(DateTime a, DateTime b)
{
  return a.isAfter(b) ? a : b;
}
like image 34
Jack Avatar answered Oct 05 '22 23:10

Jack