文章目录
概要
java封装方法 传入 localdatetime1 localdatetime2 得出二者差值转成 HH:mm:ss 字符串格式返回
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class TimeDifferenceUtil {
/**
* 计算两个LocalDateTime之间的时间差,并返回格式为HH:mm:ss的字符串
*
* @param localDateTime1 第一个时间
* @param localDateTime2 第二个时间
* @return 两个时间之间的时间差,格式为HH:mm:ss
*/
public static String getTimeDifferenceAsString(LocalDateTime localDateTime1, LocalDateTime localDateTime2) {
// 确保localDateTime1早于或等于localDateTime2
if (localDateTime1.isAfter(localDateTime2)) {
LocalDateTime temp = localDateTime1;
localDateTime1 = localDateTime2;
localDateTime2 = temp;
}
// 计算时间差
Duration duration = Duration.between(localDateTime1, localDateTime2);
// 将时间差转换为秒
long seconds = duration.getSeconds();
// 转换秒为时、分、秒
int hours = (int) (seconds / 3600);
int minutes = (int) ((seconds % 3600) / 60);
int secs = (int) (seconds % 60);
// 使用DateTimeFormatter格式化可能不是最直接的方式,但为了格式统一,这里我们使用String.format
String timeDifference = String.format("%02d:%02d:%02d", hours, minutes, secs);
// 如果你想使用DateTimeFormatter,可以这样做(但更适用于处理日期和时间)
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
// 注意:DateTimeFormatter不能直接用于Duration,因为它不是为处理时长设计的
return timeDifference;
}
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime later = now.plusHours(1).plusMinutes(30).plusSeconds(15);
String timeDifference = getTimeDifferenceAsString(now, later);
System.out.println("Time difference: " + timeDifference); // 输出:Time difference: 01:30:15
}
}