Let's suppose we have
"12:00"
and
"14:30"
How can I check whether 12:00 < 14:30
?
Let's suppose we have
"12:00"
and
"14:30"
How can I check whether 12:00 < 14:30
?
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
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, String
s 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");
}
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()
.