-3

Let's suppose we have

"12:00"

and

"14:30"

How can I check whether 12:00 < 14:30?

khelwood
  • 55,782
  • 14
  • 81
  • 108

3 Answers3

4

You can use LocalTime#isAfter or LocalTime#isBefore

import java.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        LocalTime time1 = LocalTime.parse("12:00");
        LocalTime time2 = LocalTime.parse("14:00");

        // If time1 is after time2
        System.out.println(time1.isAfter(time2));
    }
}

Output:

false
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
3

Assuming this format zero-fills leading zeros (e.g., eight and three minutes AM would be represented as "08:03"), a lexicographical comparison will do the trick. Luckily, Strings in Java are Comparable:

String a = "12:00";
String b = "14:30";

int cmp = a.compareTo(b);
if (cmp < 0) {
    System.out.println("a is earlier");
} else if (cmp == 0) {
    System.out.println("a and b are equal");
} else {
    System.out.println("b is earlier");
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Since OP showed format as `hh:mm`, i.e. 2-digit hour and minute values, and examples use 24-hour format, there is not much assuming in that assumption. – Andreas Sep 05 '20 at 23:33
2

You can either split() your strings by ":" and compare hours with hours, and if needed minutes with minutes. Or you can convert those strings to objects of the relevant classes of the java.time package and operate with the methods those classes offer, like LocalTime.isAfter() or LocalTime.isBefore().

JustAnotherDeveloper
  • 2,061
  • 2
  • 10
  • 24