package com.ruoyi.inspect.util;
|
|
import java.math.BigDecimal;
|
import java.math.RoundingMode;
|
import java.util.Objects;
|
import java.util.regex.Pattern;
|
|
/**
|
* 时分时间差计算工具类
|
* 支持格式:HH:mm(24小时制),如 08:30、23:59、00:00
|
*/
|
public class HourDiffCalculator {
|
|
// 校验HH:mm格式的正则(24小时制,小时00-23,分钟00-59)
|
private static final Pattern TIME_PATTERN = Pattern.compile("^([01]?[0-9]|2[0-3]):[0-5][0-9]$");
|
|
/**
|
* 计算两个时分字符串之间的相隔小时数
|
* @param startTime 开始时间(HH:mm,如 "08:30")
|
* @param endTime 结束时间(HH:mm,如 "17:45")
|
* @return 相隔小时数(保留2位小数,如 9.25 小时)
|
* @throws IllegalArgumentException 时间格式错误时抛出异常
|
*/
|
public static double getHourDiff(String startTime, String endTime) {
|
// 1. 校验时间格式
|
validateTimeFormat(startTime);
|
validateTimeFormat(endTime);
|
|
// 2. 解析时分字符串为总分钟数
|
int startMinutes = convertTimeToMinutes(startTime);
|
int endMinutes = convertTimeToMinutes(endTime);
|
|
// 3. 计算分钟差
|
int minuteDiff = endMinutes - startMinutes;
|
|
// 4. 转换为小时数(保留2位小数,避免精度丢失)
|
BigDecimal hourDiff = new BigDecimal(minuteDiff)
|
.divide(new BigDecimal(60), 2, RoundingMode.HALF_UP);
|
return hourDiff.doubleValue();
|
}
|
|
/**
|
* 校验时间格式是否为HH:mm
|
*/
|
private static void validateTimeFormat(String time) {
|
if (time == null || !TIME_PATTERN.matcher(time).matches()) {
|
throw new IllegalArgumentException("时间格式错误,需为HH:mm(24小时制):" + time);
|
}
|
}
|
|
/**
|
* 将HH:mm字符串转换为总分钟数(如 08:30 → 510 分钟)
|
*/
|
private static int convertTimeToMinutes(String time) {
|
String[] parts = time.split(":");
|
int hour = Integer.parseInt(parts[0]);
|
int minute = Integer.parseInt(parts[1]);
|
return hour * 60 + minute;
|
}
|
|
}
|