5

Given two LocalTime parameters in Java, I want to be able to compare the two times and see if they are equal (the same time). How would I do this?

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
FallonXay
  • 97
  • 1
  • 1
  • 3
  • 4
    Uh.. call `equals()`? – shmosel Apr 03 '18 at 00:15
  • 2
    You could start by reading the [JavaDocs](https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html) or looking at the [Date/Time Tutorials](https://docs.oracle.com/javase/tutorial/datetime/iso/datetime.html) – MadProgrammer Apr 03 '18 at 00:16
  • Possible duplicate of [Time comparison](https://stackoverflow.com/questions/2309558/time-comparison) – Duong Anh Apr 03 '18 at 02:22

2 Answers2

10

Compare using LocalTime instance methods: isBefore, isAfter, equals, and compareTo.

LocalTime lt1 = LocalTime.of( 14 , 17 ) ;
LocalTime lt2 = LocalTime.of( 21 , 29 ) ;

boolean same = lt1.equals( lt2 ) ;

equals versus isEqual

Be aware than some java.time classes (other than LocalTime) carry an isEqual method in addition to the equals method inherited from Object, with different semantics.

For example:

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
3

Try:

firstLocalTime.equals(secondLocalTime);

.equals() is available for all Objects in Java.

Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37