java 计算 LocalDatetime 相隔天数
时间: 2024-06-07 12:02:52 浏览: 145
要计算两个 `LocalDateTime` 之间相隔的天数,可以先将其转换为 `LocalDate`,然后使用 `ChronoUnit.DAYS.between()` 方法计算它们之间相隔的天数。以下是示例代码:
```java
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
LocalDateTime dateTime1 = LocalDateTime.of(2021, 9, 1, 0, 0, 0);
LocalDateTime dateTime2 = LocalDateTime.of(2021, 9, 10, 0, 0, 0);
LocalDate date1 = dateTime1.toLocalDate();
LocalDate date2 = dateTime2.toLocalDate();
long daysBetween = ChronoUnit.DAYS.between(date1, date2);
System.out.println("相隔天数:" + daysBetween);
}
}
```
输出结果为:
```
相隔天数:9
```
阅读全文