Java 如何算出两个yyyyMMddHHmmss格式的时间字符串的00:00:00格式的时长
时间: 2023-08-18 07:08:33 浏览: 162
可以使用Java中的`SimpleDateFormat`类将时间字符串转换为`Date`对象,然后再计算两个`Date`对象之间的时间差。
具体做法如下:
1. 创建两个`SimpleDateFormat`对象,用于将时间字符串转换为`Date`对象:
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
```
2. 分别使用上述两个`SimpleDateFormat`对象将时间字符串转换为`Date`对象:
```java
Date date1 = sdf.parse(timeString1);
Date date2 = sdf.parse(timeString2);
```
3. 使用`sdf2`将`date1`和`date2`格式化为日期字符串,以便比较它们是否在同一天:
```java
String dateString1 = sdf2.format(date1);
String dateString2 = sdf2.format(date2);
```
4. 如果`date1`和`date2`在同一天,则计算它们之间的时间差,并将结果格式化为`HH:mm:ss`:
```java
if (dateString1.equals(dateString2)) {
long diff = date2.getTime() - date1.getTime();
String duration = String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(diff),
TimeUnit.MILLISECONDS.toMinutes(diff) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(diff) % TimeUnit.MINUTES.toSeconds(1));
System.out.println(duration);
} else {
System.out.println("时间不在同一天!");
}
```
完整代码示例:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String[] args) throws Exception {
String timeString1 = "20220101121212";
String timeString2 = "20220101010101";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
Date date1 = sdf.parse(timeString1);
Date date2 = sdf.parse(timeString2);
String dateString1 = sdf2.format(date1);
String dateString2 = sdf2.format(date2);
if (dateString1.equals(dateString2)) {
long diff = date2.getTime() - date1.getTime();
String duration = String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(diff),
TimeUnit.MILLISECONDS.toMinutes(diff) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(diff) % TimeUnit.MINUTES.toSeconds(1));
System.out.println(duration);
} else {
System.out.println("时间不在同一天!");
}
}
}
```
输出结果:
```
09:11:11
```
阅读全文