0

I want to compare if 2 LocalTime are equal, but only using the hours, minutes and seconds, not with all the data of the variable, like milliseconds.

How can I accomplish that?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Not a duplicate, since he is asking for `LocalTime` in Java 8 and not `java.util.Date`. – markusw Dec 06 '18 at 14:57
  • 1
    Put an example of the code you have, and where you would like the comparison to take place – jbx Dec 06 '18 at 15:12
  • This comparator should do it: `Comparator.comparingInt(LocalTime::getMinute).thenComparing(LocalTime::getSecond)` – jbx Dec 06 '18 at 15:15

4 Answers4

3

Considering the last edited version of your question, you can compare two instances of LocalTime by just hour, minute and second part this way:

LocalTime lt1 = LocalTime.now(); // usually contains seconds and subseconds
LocalTime lt2 = LocalTime.of(22, 48); // example with zero second part

boolean isEqualInSecondPrecision = 
    lt1.truncatedTo(ChronoUnit.SECONDS).equals(lt2.truncatedTo(ChronoUnit.SECONDS));
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
1

You can set the hours to the same in both with myTime.withHour(0), than you have left only the minutes and seconds that differ and you are able to come these 2 times.

Example:

time1 = ...
time2 = ...

if (time1.withHour(0).equals(time2.withHour(0))) {
  System.out.println('Minutes and Seconds of time1 and time2 are equal!');
}
markusw
  • 1,975
  • 16
  • 28
  • 1
    This is the right answer, except that the original question has been edited and is now asking how to compare hours/minutes/seconds while ignoring fractional seconds, so it should be `withNano` rather than withHour. – VGR Dec 06 '18 at 15:49
1

You can just set both nanos to one number to make them the same with each other, say, zero, to compare them.

LocalTime localTime1 = LocalTime.of(1, 2, 3, 100);
LocalTime localTime2 = LocalTime.of(1, 2, 3, 47);
if (localTime1.withNano(0).equals(localTime2.withNano(0))){
    System.out.println("something");
}
Bing Zhao
  • 568
  • 6
  • 19
  • I’d tend to prefer `localTime1.truncatedTo(ChronoUnit.SECONDS)` (and similarly for `localTime2`). So the reader would not need to wonder whether also milliseconds and microseconds are set to 0 (which they are, but not everyone knows by heart). – Ole V.V. Dec 07 '18 at 12:25
  • @OleV.V. Both create a new instance of `LocalTime` while implementation of `LocalTime.truncatedTo` is even more complicated. Well, no big deal, choose what you like. – Bing Zhao Dec 07 '18 at 12:34
0

Something like this

LocalTime t1=..
LocalTime t2=..
LocalTime.of(t1.getHour(), t1.getMinutes()).compareTo(LocalTime.of(t2.getHour(),t2.getMinutes());

with also seconds if u need of course

Raffaele
  • 461
  • 1
  • 7
  • 20