How to compare two java.time.Period in java 8?

yetanothercoder picture yetanothercoder · Dec 25, 2016 · Viewed 9.7k times · Source

How do I compare two Periods in java 8?

E.g.

Period one = Period.of(10,0,0);
Period two = Period.of(8,0,0);

here in this case one is greater than two.

Answer

Honza Zidek picture Honza Zidek · Feb 17, 2017

It is true that the comparison of two Period objects does not make sense in a general case, due to the undefined standard length of a month.

However, in many situations you can quite well live with an implementation similar to that which follows. The contract will be similar to the contract of compareTo():

public int comparePeriodsApproximately(Period p1, Period p2) {
    return period2Days(p1) - period2Days(p2);
}

private int period2Days(Period p) {
    if (p == null) {
        return 0;
    }
    return (p.getYears() * 12 + p.getMonths()) * 30 + p.getDays();
}