java时间戳计算时间间隔
时间: 2023-09-11 21:04:33 浏览: 75
Java中可以使用`java.util.Date`和`java.time.LocalDateTime`类来计算时间间隔。
方法一:使用java.util.Date类
```java
import java.util.Date;
public class TimeDiff {
public static void main(String[] args) {
Date startTime = new Date(1630368000000L); // 2021-08-31 00:00:00
Date endTime = new Date(1630454400000L); // 2021-09-01 00:00:00
long diffInMillies = Math.abs(endTime.getTime() - startTime.getTime());
long diff = diffInMillies / (60 * 60 * 1000); // 计算小时数
System.out.println("时间间隔为:" + diff + "小时");
}
}
```
方法二:使用java.time.LocalDateTime类
```java
import java.time.LocalDateTime;
import java.time.Duration;
public class TimeDiff {
public static void main(String[] args) {
LocalDateTime startTime = LocalDateTime.of(2021, 8, 31, 0, 0, 0);
LocalDateTime endTime = LocalDateTime.of(2021, 9, 1, 0, 0, 0);
Duration duration = Duration.between(startTime, endTime);
long diff = Math.abs(duration.toHours()); // 计算小时数
System.out.println("时间间隔为:" + diff + "小时");
}
}
```
阅读全文