可以使用until()
Java中Instant类中的方法来计算两个即时对象之间的时间。该方法需要两个参数,即结束时刻和时间单位来测量时间。它返回两个即时对象之间的时间。
演示此的程序如下所示-
import java.time.*; import java.time.temporal.ChronoUnit; public class Demo { public static void main(String[] args) { Instant i1 = Instant.parse("2019-01-13T11:45:13.00Z"); Instant i2 = Instant.parse("2019-01-13T15:30:12.00Z"); long time = i1.until(i2, ChronoUnit.HOURS); System.out.println("Instant object i1 is: " + i1); System.out.println("Instant object i2 is: " + i2); System.out.println("\nThe time between two instant objects in hours is: " + time); } }
输出结果
Instant object i1 is: 2019-01-13T11:45:13Z Instant object i2 is: 2019-01-13T15:30:12Z The time between two instant objects in hours is: 3
现在让我们了解上面的程序。
显示两个即时对象。然后,使用该until()
方法计算并显示这两个即时对象之间的时间。演示这的代码片段如下-
Instant i1 = Instant.parse("2019-01-13T11:45:13.00Z"); Instant i2 = Instant.parse("2019-01-13T15:30:12.00Z"); long time = i1.until(i2, ChronoUnit.HOURS); System.out.println("Instant object i1 is: " + i1); System.out.println("Instant object i2 is: " + i2); System.out.println("\nThe time between two instant objects in hours is: " + time);