Java中的即时compareTo()方法
可以使用compareTo()JavaInstant类中的方法比较两个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()方法比较它们,并使用ifelse语句显示结果。演示此代码段如下所示:
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");热门推荐
10 祝福语年轻回复文案简短
11 生日祝福语简短激励女生
12 收围巾的祝福语简短
13 剪简短的新年祝福语
14 五十二新年祝福语简短
15 叔叔生日祝福语简短搞笑
16 简短古文生日祝福语
17 收到公公生日祝福语简短
18 宝宝100日简短祝福语