近期遇到这样一个场景,需要将输入的“20s”解析成200ms,或者“1min”解析成60000ms等,没找到合适的工具类,暂且自己写了一个记录下来。
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import java.util.concurrent.TimeUnit;
/**
* @author: sea
* @date: 2022/10/18 18:35
*/
public class TimeUtil {
public static long parseUnitTimeToMillSeconds(String timeWithUnit) {
Pair<Long, TimeUnit> pair = parseAndSplitTimeWithUnit(timeWithUnit);
return pair.getRight().toMillis(pair.getLeft());
}
/**
* 将带有时间单位的字符串进行分割
* 比如:200ms 分割成 200和ms
* 支持的时间单位:ns纳秒,us微妙,ms毫秒,s秒,min分钟,h小时,d天
* 默认是ms,比如200,会解析成200ms
* @param timeWithUnit
* @return
*/
public static Pair<Long, TimeUnit> parseAndSplitTimeWithUnit(String timeWithUnit) {
if (StringUtils.isBlank(timeWithUnit)) {
return Pair.of(0L, TimeUnit.MILLISECONDS);
}
char[] chars = timeWithUnit.toCharArray();
int length = chars.length;
int position = length - 1;
while (position >= 0 && Character.isLetter(chars[position])) {
position--;
}
position = Math.min(position + 1, length);
String timeStr = StringUtils.substring(timeWithUnit, 0, position);
long time = Long.parseLong(StringUtils.trim(timeStr));
String unitStr = StringUtils.substring(timeWithUnit, position, length);
if (StringUtils.isBlank(unitStr)) {
return Pair.of(time, TimeUnit.MILLISECONDS);
}
TimeUnit unit = convertTimeUnit(unitStr);
if (unit == null) {
throw new IllegalArgumentException("不支持该时间单位:" + unitStr);
}
return Pair.of(time, unit);
}
private static TimeUnit convertTimeUnit(String unitStr) {
TimeUnit timeUnit = null;
unitStr = StringUtils.lowerCase(unitStr);
unitStr = StringUtils.trim(unitStr);
switch (unitStr) {
case "ns":
timeUnit = TimeUnit.NANOSECONDS;
break;
case "us":
timeUnit = TimeUnit.MICROSECONDS;
break;
case "ms":
timeUnit = TimeUnit.MILLISECONDS;
break;
case "s":
timeUnit = TimeUnit.SECONDS;
break;
case "min":
timeUnit = TimeUnit.MINUTES;
break;
case "h":
timeUnit = TimeUnit.HOURS;
break;
case "d":
timeUnit = TimeUnit.DAYS;
break;
}
System.out.println(timeUnit);
return timeUnit;
}
}