Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 685
yetanothercoder Avatar asked Dec 25 '16 11:12

yetanothercoder


People also ask

How do you compare two periods in Java?

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.

What is the difference between two LocalDateTime in Java 8?

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.


3 Answers

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();
}
like image 173
Honza Zidek Avatar answered Oct 17 '22 19:10

Honza Zidek


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));
like image 3
Rohit Gulati Avatar answered Oct 17 '22 19:10

Rohit Gulati


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()); 
like image 1
Radu Linu Avatar answered Oct 17 '22 21:10

Radu Linu