LocalDateTime 添加时间
时间: 2023-10-14 19:02:29 浏览: 51
要将时间添加到 LocalDateTime 对象,您可以使用 LocalDateTime 的 `plus` 方法。这个方法接受一个 `TemporalAmount` 参数,用于指定要添加的时间量。以下是一个示例代码:
```java
LocalDateTime dateTime = LocalDateTime.now(); // 获取当前时间
LocalDateTime newDateTime = dateTime.plusHours(2); // 添加2小时
System.out.println("原始时间:" + dateTime);
System.out.println("添加2小时后的时间:" + newDateTime);
```
在上面的示例中,我们获取了当前的 LocalDateTime 对象 `dateTime`,然后使用 `plusHours` 方法添加了 2 小时,并将结果存储在 `newDateTime` 中。最后,我们打印出原始时间和添加时间后的结果。
您可以根据需要使用其他方法,如 `plusMinutes`、`plusDays` 等,来添加不同的时间量。请注意,`plus` 方法会返回一个新的 LocalDateTime 对象,并不会修改原始对象。
相关问题
LocalDateTime添加天数
LocalDateTime添加天数的方法是使用plusDays()方法。以下是一个示例代码:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeExample {
public static void main(String[] args) {
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("当前日期时间: " + currentDateTime);
LocalDateTime newDateTime = currentDateTime.plusDays(7);
System.out.println("添加7天后的日期时间: " + newDateTime);
}
}
```
java 添加LocalDateTime数组
在Java中,可以通过以下方式创建并添加LocalDateTime数组:
```
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime[] dateTimeArray = new LocalDateTime; //创建长度为5的LocalDateTime数组
dateTimeArray = LocalDateTime.now(); //将当前时间添加到数组第一个位置
dateTimeArray = LocalDateTime.of(2021, 8, 1, 12, 0); //将2021年8月1日12:00添加到数组第二个位置
dateTimeArray = LocalDateTime.parse("2021-08-02T15:30:00"); //将2021年8月2日15:30添加到数组第三个位置
dateTimeArray = LocalDateTime.of(2021, 8, 3, 18, 0, 30); //将2021年8月3日18:00:30添加到数组第四个位置
dateTimeArray = LocalDateTime.of(2021, 8, 4, 20, 15); //将2021年8月4日20:15添加到数组第五个位置
}
}
```
以上代码演示了如何创建一个长度为5的LocalDateTime数组,并且将不同的LocalDateTime对象添加到数组中不同的位置。