可以使用compareTo()
Java Instant类中的方法比较两个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("第一个Instant对象是: " + i1); System.out.println("第二个Instant对象是: " + i2); int val = i1.compareTo(i2); if(val > 0) System.out.println("\nThe first Instant object is greater than the second Instant object"); else if(val < 0) System.out.println("\nThe first Instant object is lesser than the second Instant object"); else System.out.println("\nThe Instant objects are equal"); } }
输出结果
第一个Instant对象是: 2019-01-13T18:35:19Z 第二个Instant对象是: 2019-01-13T16:10:35Z The first Instant object is greater than the second Instant object
现在让我们了解上面的程序。
首先显示两个即时对象。然后使用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("第一个Instant对象是: " + i1); System.out.println("第二个Instant对象是: " + i2); int val = i1.compareTo(i2); if(val > 0) System.out.println("\nThe first Instant object is greater than the second Instant object"); else if(val < 0) System.out.println("\nThe first Instant object is lesser than the second Instant object"); else System.out.println("\nThe Instant objects are equal");