java怎么计算时间差
时间: 2023-09-12 09:03:26 浏览: 86
java计算时间差的方法
5星 · 资源好评率100%
在Java中,可以使用Java 8引入的时间API(java.time包)来计算时间差。具体步骤如下:
1. 使用LocalDateTime类获取两个时间点的实例:
```java
LocalDateTime startTime = LocalDateTime.now();
LocalDateTime endTime = LocalDateTime.of(2021, 8, 23, 10, 0, 0);
```
2. 使用Duration类计算时间差:
```java
Duration duration = Duration.between(startTime, endTime);
```
3. 获取时间差的小时数、分钟数、秒数等:
```java
long hours = duration.toHours();
long minutes = duration.toMinutes() % 60;
long seconds = duration.getSeconds() % 60;
```
完整代码如下:
```java
import java.time.Duration;
import java.time.LocalDateTime;
public class TimeDifference {
public static void main(String[] args) {
LocalDateTime startTime = LocalDateTime.now();
LocalDateTime endTime = LocalDateTime.of(2021, 8, 23, 10, 0, 0);
Duration duration = Duration.between(startTime, endTime);
long hours = duration.toHours();
long minutes = duration.toMinutes() % 60;
long seconds = duration.getSeconds() % 60;
System.out.printf("时间差:%d小时 %d分钟 %d秒", hours, minutes, seconds);
}
}
```
阅读全文