可以使用Java中LocalDateTime类中的till()方法获取两个LocalDateTime对象之间的差异。此方法需要两个参数,即LocalDateTime对象的结束日期和Temporal单位。同样,它以指定的时间单位返回两个LocalDateTime对象之间的差。
演示此的程序如下所示-
import java.time.*; import java.time.temporal.*; public class Demo { public static void main(String[] args) { LocalDateTime ldt1 = LocalDateTime.parse("2019-02-18T23:15:30"); LocalDateTime ldt2 = LocalDateTime.parse("2019-02-19T12:21:30"); System.out.println("The first LocalDateTime is: " + ldt1); System.out.println("The second LocalDateTime is: " + ldt2); System.out.println("\nThe difference between two LocalDateTimes in hours is: " + ldt1.until(ldt2, ChronoUnit.HOURS)); } }
输出结果
The first LocalDateTime is: 2019-02-18T23:15:30 The second LocalDateTime is: 2019-02-19T12:21:30 The difference between two LocalDateTimes in hours is: 13
现在让我们了解上面的程序。
首先,显示两个LocalDateTime对象。然后,使用till()方法获得它们之间的小时差并显示出来。演示这的代码片段如下-
LocalDateTime ldt1 = LocalDateTime.parse("2019-02-18T23:15:30"); LocalDateTime ldt2 = LocalDateTime.parse("2019-02-19T12:21:30"); System.out.println("The first LocalDateTime is: " + ldt1); System.out.println("The second LocalDateTime is: " + ldt2); System.out.println("\nThe difference between two LocalDateTimes in hours is: " + ldt1.until(ldt2, ChronoUnit.HOURS));