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.
The equals() method of Period class in Java is used to check if two given periods are equal or not. The comparison is based on the type Period and each of the three years, months and date.
Here's a way to calculate the difference although not necessarily the fastest: LocalDateTime fromDateTime = LocalDateTime. of(1984, 12, 16, 7, 45, 55); LocalDateTime toDateTime = LocalDateTime. of(2014, 9, 10, 6, 40, 45); LocalDateTime tempDateTime = LocalDateTime.
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();
}
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));
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With