英文:
How can I check whether hh:mm < hh:mm
问题
让我们假设我们有
"12:00"
和
"14:30"
我如何检查 12:00 < 14:30
?
英文:
Let's suppose we have
"12:00"
and
"14:30"
How can I check whether 12:00 < 14:30
?
答案1
得分: 4
## 你可以使用 [LocalTime#isAfter][1] 或者 [`LocalTime#isBefore`][2]
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");
// 如果 time1 在 time2 之后
System.out.println(time1.isAfter(time2));
}
}
**输出:**
false
[1]: https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html#isAfter-java.time.LocalTime-
[2]: https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html#isBefore-java.time.LocalTime-
英文:
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
答案2
得分: 3
假设这个格式会在前导零处填充零(例如,上午八点零三分将表示为“08:03”),词典比较即可解决问题。幸运的是,Java 中的 String
是 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");
}
英文:
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");
}
答案3
得分: 2
你可以使用 split()
方法通过 ":" 分割字符串,然后将小时与小时进行比较,如果需要,可以将分钟与分钟进行比较。或者你可以将这些字符串转换为 java.time 包 中相关类的对象,然后使用这些类提供的方法进行操作,例如 LocalTime.isAfter()
或 LocalTime.isBefore()
。
英文:
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()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论