Comparing Periods for Equality – Date and Time

Comparing Periods for Equality

The Period class overrides the equals() and hashCode() methods of the Object class, but the class does not implement the Comparable<E> interface. The value of each date unit is compared individually, and must have the same value to be considered equal. A period of 1 year and 14 months is not equal to a period of 2 years and 2 months, or to a period of 26 months. For this reason, Period objects do not implement the Comparable<E> interface.

Click here to view code image

Period px = Period.of(1, 14, 0);
Period py = Period.of(2, 2, 0);
Period pz = Period.ofMonths(26);
System.out.println(px.equals(py));           // false
System.out.println(px.equals(pz));           // false
System.out.println(px.equals(Period.ZERO));  // false

boolean equals(Object obj)

Determines whether this period is equal to another period, meaning that each corresponding date unit has the same value.

int hashCode()

Returns a hash code for this period.

Creating Modified Copies of Periods

The Period class provides with methods to set a new value for each date unit individually, while the values of the other date units remain unchanged. Note that each method call returns a new Period object, and chaining method calls work as expected.

Click here to view code image

Period p5 = Period.of(2, 1, 30) // P2Y1M30D
    .withYears(3)               // P3Y1M30D, sets the number of years
    .withMonths(16)             // P3Y16M30D, sets the number of months
    .withDays(1);               // P3Y16M1D, sets the number of days

Period withYears(int years)
Period withMonths(int months)
Period withDays(int days)

Return a copy of this period where a specific date unit is set to the value of the argument. The values of the other date units are not affected.