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

半城伤御伤魂 提交于 2020-05-27 05:58:25

问题


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.


回答1:


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();
}



回答2:


Rightly said by JB Nizet. You cannot compare Periods, as per java doc in Period class there is similar class to Period (Duration) available in java, you can use that depends on your business requirement.

"Durations and periods differ in their treatment of daylight savings time when added to ZonedDateTime. A Duration will add an exact number of seconds, thus a duration of one day is always exactly 24 hours. By contrast, a Period will add a conceptual day, trying to maintain the local time."

Period period = Period.of(10, 0, 0);
Period period2 = Period.of(10, 0, 0);

// No compareTo method in period
System.out.println(period.compareTo(period2));

Duration duration = Duration.ofDays(3);
Duration duration2 = Duration.ofDays(3);

// Can compare durations as it gives you the exact time
System.out.println(duration.compareTo(duration2));



回答3:


In case you have a period of months and period of years you can do as follows:

Period periodOfMonths = Period.ofMonths(16);
Period periodOfYears = Period.ofYears(1);

// Check if period of months is ghreather that the period of years
System.out.println(periodOfMonths.toTotalMonths() > periodOfYears.toTotalMonths()); 


来源:https://stackoverflow.com/questions/41320609/how-to-compare-two-java-time-period-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!