-2

Given two strings like 02:03:45 and 10:04:20 which represents hh:mm:ss
Is there any efficient way to determine which is lesser and which is more?

My thoughts:
I thought of splitting them by : and then checking. But I was wondering if

there is a neat way to do it

sunny
  • 149
  • 8
  • 1
    How about using [`compareTo`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#compareTo-java.lang.String-) on the strings? Doesn't that give you the answer you want? – khelwood Jul 30 '21 at 11:59
  • 1
    If the time is formatted in 24 hours format and you only want to know which one is lesser/greater you can simply use the String `compareTo` method https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#compareTo-java.lang.String- – Robert Jul 30 '21 at 11:59
  • Just convert them to `LocalTime` (example: https://stackoverflow.com/questions/30788369/coverting-string-to-localtime-with-without-nanoofseconds) and compare them. – Ervin Szilagyi Jul 30 '21 at 12:00
  • Please visit this link [Android - Time Comparison “hh:mm:ss a” format](https://stackoverflow.com/questions/31883783/android-time-comparison-hhmmss-a-format) I hope it works. – Sajid Ali Jul 30 '21 at 12:17
  • @user16320675 If the OP's strings did not have leading zeroes, I would not have suggested it. – khelwood Jul 30 '21 at 23:04

1 Answers1

7

You can do it in that way:

 LocalTime time1 = LocalTime.parse("02:03:45");
 LocalTime time2 = LocalTime.parse("10:04:20");

an then call: time1.compareTo(time2)

Matt
  • 1,298
  • 1
  • 12
  • 31