java 计算 两个yyyy-MM-dd HH:mm:ss 时间两个字符串的小时差值
时间: 2024-08-27 18:03:13 浏览: 293
在 Java 中,你可以使用 `java.time` 包下的 `LocalDateTime` 类来计算两个 `yyyy-MM-dd HH:mm:ss` 格式的时间字符串之间的小时差值。首先,你需要将字符串转换成 `LocalDateTime` 对象,然后计算它们之间的时间差,最后获取小时数。以下是步骤:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String time1 = "2023-06-01 12:00:00";
String time2 = "2023-06-02 15:30:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime1 = LocalDateTime.parse(time1, formatter);
LocalDateTime dateTime2 = LocalDateTime.parse(time2, formatter);
// 计算时间差
Duration duration = Duration.between(dateTime1, dateTime2);
// 提取小时数并打印结果
int hoursDifference = (int) duration.toHours();
System.out.println("小时差值: " + hoursDifference);
}
}
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)