如何检查 hh:mm 是否小于 hh:mm。

huangapple go评论81阅读模式
英文:

How can I check whether hh:mm < hh:mm

问题

让我们假设我们有

"12:00"

"14:30"

我如何检查 12:00 < 14:30

英文:

Let's suppose we have

&quot;12:00&quot;

and

&quot;14:30&quot;

How can I check whether 12:00 &lt; 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(&quot;12:00&quot;);
		LocalTime time2 = LocalTime.parse(&quot;14:00&quot;);

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

Output:

false

答案2

得分: 3

假设这个格式会在前导零处填充零(例如,上午八点零三分将表示为“08:03”),词典比较即可解决问题。幸运的是,Java 中的 StringComparable 的:

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, Strings in Java are Comparable:

String a = &quot;12:00&quot;;
String b = &quot;14:30&quot;;

int cmp = a.compareTo(b);
if (cmp &lt; 0) {
    System.out.println(&quot;a is earlier&quot;);
} else if (cmp == 0) {
    System.out.println(&quot;a and b are equal&quot;);
} else {
    System.out.println(&quot;b is earlier&quot;);
}

答案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().

huangapple
  • 本文由 发表于 2020年9月6日 05:13:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63758574.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定