可以使用plusHours()
Java中LocalDateTime类中的方法获取其中添加了几个小时的LocalDateTime对象的不可变副本。此方法需要一个参数,即要添加的小时数,并且它返回带有已添加的小时数的LocalDateTime对象。
演示此的程序如下所示-
import java.time.*; public class Demo { public static void main(String[] args) { LocalDateTime ldt = LocalDateTime.now(); System.out.println("The current LocalDateTime is: " + ldt); System.out.println("The LocalDateTime with 3 hours added is: " + ldt.plusHours(3)); } }
输出结果
The current LocalDateTime is: 2019-02-18T09:17:08.872 The LocalDateTime with 3 hours added is: 2019-02-18T12:17:08.872
现在让我们了解上面的程序。
首先显示当前的LocalDateTime。然后使用该plusHours()
方法获得LocalDateTime的不可变副本,其中添加了3个小时,并将其显示出来。演示这的代码片段如下-
LocalDateTime ldt = LocalDateTime.now(); System.out.println("The current LocalDateTime is: " + ldt); System.out.println("The LocalDateTime with 3 hours added is: " + ldt.plusHours(3));