簡體   English   中英

我該如何縮短這個

[英]how do I shorten this

有什么辦法可以縮短這段代碼? 在代碼中,微秒的時間被轉換為分鍾和秒。 例如 305862000 毫秒 = 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 常用 DurationFormatUtils: https://github.com/apache/commons-lang

boolean padWithZeros = true;
DurationFormatUtils.formatDuration(millis, "**mm:ss**", padWithZeros);

沒有圖書館(來自 Zabuzard 的評論),請參閱:

如何在 java 中格式化持續時間? (例如格式 H:MM:SS)

使用String.format()格式化帶有前導零的數字。

public static String timeFormatter(long microtime) {
    if (microtime < 0)
        throw new IllegalArgumentException("Negative time value provided: " + microtime);
    if (microtime >= 6000000000L/*100 mins*/)
        throw new IllegalArgumentException("Time value exceeds allowed format: " + microtime);
    long seconds = microtime / 1000000;
    return String.format("%02d:%02d", seconds / 60, seconds % 60);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM