Java如何找到两个时间之间的差值?
下面的代码片段向您展示了如何找到LocalTime类表示的两个时间对象之间的差异。要获得两个LocalTime对象之间的差异,我们可以使用持续时间.between()方法。这个方法返回一个Duration对象,为了得到以秒为单位的差异,我们调用getSeconds()方法。
这里是一个代码片段来演示它。
package org.nhooo.example.datetime; import java.time.*; public class TimeDifference { public static void main(String[] args) { LocalTime start = LocalTime.now(); LocalTime end = LocalTime.of(16, 59, 55); Duration duration = Duration.between(start, end); System.out.printf("Seconds between %s and %s is: %s seconds.%n", start, end, duration.getSeconds()); diffLocalDateTime(); diffInstant(); } /** * 两个 LocalDateTime 对象之间的差异。 */ public static void diffLocalDateTime() { LocalDateTime dt1 = LocalDateTime.now(); LocalDateTime dt2 = LocalDateTime.now(ZoneId.of("GMT+0")); Duration duration = Duration.between(dt1, dt2); System.out.printf("Duration = %s seconds.%n", duration.getSeconds()); } /** * 两个瞬间对象之间的区别。 */ public static void diffInstant() { Instant instant1 = Instant.now(); Instant instant2 = Instant.EPOCH; Duration duration = Duration.between(instant1, instant2); System.out.printf("Duration = %s seconds.%n", duration.getSeconds()); } }
使用Duration.between()还可以获得两个LocalDateTime对象和两个Instant对象之间的差异,如上面代码片段中的diffLocalDateTime()方法和diffInstant方法所示。
代码段的结果:
Seconds between 16:58:15.863 and 16:59:55 is: 99 seconds. Duration = -28800 seconds. Duration = -1455181096 seconds.