Java 中的 Instant compareTo() 方法
可以使用 Java 中 Instant 类的 compareTo() 方法比较两个 Instant 对象。此方法需要一个参数,即要比较的 Instant 对象。
如果第一个 Instant 对象大于第二个 Instant 对象,则它返回正数,如果第一个 Instant 对象小于第二个 Instant 对象,则它返回负数,如果两个 Instant 对象相等,则它返回零。
展示此方法的程序如下所示
示例
import java.time.*; public class Demo { public static void main(String[] args) { Instant i1 = Instant.parse("2019-01-13T18:35:19.00Z"); Instant i2 = Instant.parse("2019-01-13T16:10:35.00Z"); System.out.println("The first Instant object is: " + i1); System.out.println("The second Instant object is: " + i2); int val = i1.compareTo(i2); if(val > 0) System.out.println("
The first Instant object is greater than the second Instant object"); else if(val < 0) System.out.println("
The first Instant object is lesser than the second Instant object"); else System.out.println("
The Instant objects are equal"); } }
输出
The first Instant object is: 2019-01-13T18:35:19Z The second Instant object is: 2019-01-13T16:10:35Z The first Instant object is greater than the second Instant object
下面我们来理解一下上述程序。
首先显示两个 Instant 对象。然后,使用 compareTo() 方法对其进行比较,并使用 if else 语句显示结果。演示此方法的代码片段如下
Instant i1 = Instant.parse("2019-01-13T18:35:19.00Z"); Instant i2 = Instant.parse("2019-01-13T16:10:35.00Z"); System.out.println("The first Instant object is: " + i1); System.out.println("The second Instant object is: " + i2); int val = i1.compareTo(i2); if(val > 0) System.out.println("
The first Instant object is greater than the second Instant object"); else if(val < 0) System.out.println("
The first Instant object is lesser than the second Instant object"); else System.out.println("
The Instant objects are equal");
广告