add Time.parseToMS(String)
This commit is contained in:
@ -255,6 +255,51 @@ public class Time {
|
||||
return Instant.ofEpochMilli(unixTime).atZone(ZoneId.systemDefault()).toLocalDateTime();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 将时间字符串解析为毫秒值
|
||||
*
|
||||
* <p>支持的格式示例:
|
||||
* <pre>
|
||||
* 10 = 10
|
||||
* 10ms = 10
|
||||
* 10s = 10,000
|
||||
* 10m = 600,000
|
||||
* 10h = 36,000,000
|
||||
* 10d = 10D = 10 d = 864,000,000
|
||||
* 10.5d = 907,200,000
|
||||
* </pre>
|
||||
*
|
||||
* @param timeStr 时间字符串
|
||||
* @return 毫秒
|
||||
* @throws IllegalArgumentException 输入格式无效
|
||||
*/
|
||||
public static long parseToMS(String timeStr) {
|
||||
if (TimiJava.isEmpty(timeStr)) {
|
||||
throw new IllegalArgumentException("not found timeStr");
|
||||
}
|
||||
String normalized = timeStr.replaceAll("\\s+", "").toLowerCase();
|
||||
|
||||
Pattern pattern = Pattern.compile("^(\\d+(?:\\.\\d+)?)(ms|[dhms])?$");
|
||||
Matcher matcher = pattern.matcher(normalized);
|
||||
if (!matcher.matches()) {
|
||||
throw new IllegalArgumentException("invalid format: " + timeStr);
|
||||
}
|
||||
double value = Double.parseDouble(matcher.group(1));
|
||||
String unit = matcher.group(2);
|
||||
if (TimiJava.isEmpty(unit) || unit.equals("ms")) {
|
||||
return Math.round(value);
|
||||
}
|
||||
double multiplier = switch (unit) {
|
||||
case "s" -> Time.S;
|
||||
case "m" -> Time.M;
|
||||
case "h" -> Time.H;
|
||||
case "d" -> Time.D;
|
||||
default -> throw new IllegalArgumentException("invalid format unit: " + unit);
|
||||
};
|
||||
return Math.round(value * multiplier);
|
||||
}
|
||||
|
||||
/**
|
||||
* 媒体时间操作
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user