我该如何简化

问题描述 投票:0回答:2

有什么办法可以缩短这段代码?在代码中,微秒的时间转换为分钟和秒。例如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;
}
java eclipse
2个回答
5
投票

计算

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的评论,请参阅:

How to format a duration in java? (e.g format H:MM:SS)


0
投票

使用String.format()格式化带前导零的数字。

String.format()
© www.soinside.com 2019 - 2024. All rights reserved.