有什么办法可以缩短这段代码?在代码中,微秒的时间转换为分钟和秒。例如305862000 ms = 05:05(5分钟:5秒)。
public static String timeFormatter (long microtime) {
String time = null, timemin = null, timesec = null;
long min = 0;
long sec = 0;
// check if time is negative
if (microtime < 0) {
throw new RuntimeException("Negativ time value provided");
} else {
min = (long) (microtime/(Math.pow((double) 10,(double) 6))/60);
if (min < 10) {
timemin = "0" + min;
// check if time is too long
} else if (min > 99) {
throw new RuntimeException("Time value exceeds allowed format");
} else {
timemin = min + "";
}
microtime = (long) (microtime - min*60*Math.pow((double) 10, (double) 6));
sec = (long) (microtime/Math.pow(10, 6));
if (sec < 10) {
timesec = "0" + sec;
} else {
timesec = sec + "";
}
time = timemin + ":" + timesec;
}
return time;
}
long milliseconds = microtime/1000;
Duration durationInMilliseconds = Duration.ofMillis(milliseconds);
使用Apache Common DurationFormatUtils:https://github.com/apache/commons-lang
boolean padWithZeros = true;
DurationFormatUtils.formatDuration(millis, "**mm:ss**", padWithZeros);
没有库(来自Zabuzard的评论,请参阅:
使用String.format()
格式化带前导零的数字。
String.format()