簡體   English   中英

從納秒級獲取人類可讀時間

[英]Get Human readable time from nanoseconds

我正在嘗試使用System.nanoTime()實現 ETA 功能

startTime = System.nanoTime()
Long elapsedTime = System.nanoTime() - startTime;
Long allTimeForDownloading = (elapsedTime * allBytes / downloadedBytes);

Long remainingTime = allTimeForDownloading - elapsedTime;

但是我不知道如何獲得人類可讀的納秒形式; 例如: 1d 1h36s3m 50s

我怎樣才能做到這一點?

我會說這兩個答案都是正確的,但無論如何這里是一個接受納米時間並返回人類可讀字符串的函數的更短版本。

private String getReadableTime(Long nanos){

    long tempSec    = nanos/(1000*1000*1000);
    long sec        = tempSec % 60;
    long min        = (tempSec /60) % 60;
    long hour       = (tempSec /(60*60)) % 24;
    long day        = (tempSec / (24*60*60)) % 24;
    
    return String.format("%dd %dh %dm %ds", day,hour,min,sec);

}

為了獲得最大的精度,您可以使用浮點除法和向上舍入來代替整數除法。

這是我的舊代碼,您也可以將其轉換為天數。

  private String calculateDifference(long timeInMillis) {
    String hr = "";
    String mn = "";
    long seconds = (int) ((timeInMillis) % 60);
    long minutes = (int) ((timeInMillis / (60)) % 60);
    long hours = (int) ((timeInMillis / (60 * 60)) % 24);

    if (hours < 10) {
        hr = "0" + hours;
    }
    if (minutes < 10) {
        mn = "0" + minutes;
    }
    textView.setText(Html.fromHtml("<i><small;text-align: justify;><font color=\"#000\">" + "Total shift time: " + "</font></small; text-align: justify;></i>" + "<font color=\"#47a842\">" + hr + "h " + mn + "m " + seconds + "s" + "</font>"));
    return hours + ":" + minutes + ":" + seconds;
}
 }

如果remainingTime納秒為單位,只需進行數學運算並將值附加到StringBuilder

long remainingTime = 5023023402000L;
StringBuilder sb = new StringBuilder();
long seconds = remainingTime / 1000000000;
long days = seconds / (3600 * 24);
append(sb, days, "d");
seconds -= (days * 3600 * 24);
long hours = seconds / 3600;
append(sb, hours, "h");
seconds -= (hours * 3600);
long minutes = seconds / 60;
append(sb, minutes, "m");
seconds -= (minutes * 60);
append(sb, seconds, "s");
long nanos = remainingTime % 1000000000;
append(sb, nanos, "ns");

System.out.println(sb.toString());

// auxiliary method
public void append(StringBuilder sb, long value, String text) {
    if (value > 0) {
        if (sb.length() > 0) {
            sb.append(" ");
        }
        sb.append(value).append(text);
    }
}

上面的輸出是:

1 小時 23 米 43 秒 23402000 納秒

(1 小時 23 分 43 秒 23402000 納秒)。

這是我的建議。 它基於這樣一個事實,即TimeUnit.values()中的單位從最小(納秒)到最長(天)排序。

    private static String getHumanReadableTime(long nanos) {
        TimeUnit unitToPrint = null;
        String result = "";
        long rest = nanos;
        for(TimeUnit t: TimeUnit.values()) {
            if (unitToPrint == null) {
                unitToPrint = t;
                continue;
            }
            // convert 1 of "t" to "unitToPrint", to get the conversion factor
            long factor = unitToPrint.convert(1, t);
            long value = rest % factor;
            rest /= factor;

            result = value + " " + unitToPrint + " " + result;

            unitToPrint = t;
            if (rest == 0) {
                break;
            }
        }
        if (rest != 0) {
            result = rest + " " + unitToPrint + " " + result;
        }

        return result.trim();
    }

getHumanReadableTime(139543185092L)的輸出將是

2 MINUTES 19 SECONDS 543 MILLISECONDS 185 MICROSECONDS 92 NANOSECONDS

java.time

您可以使用java.time.Duration ,它以ISO-8601 標准為模型,並作為JSR-310 實現的一部分隨Java-8引入。 Java-9中,引入了一些更方便的方法。

演示:

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        long elapsedTime = 12345678987654321L;

        Duration duration = Duration.ofNanos(elapsedTime);
        // Default format
        System.out.println(duration);

        // Custom format
        // ####################################Java-8####################################
        String formattedElapsedTime = String.format(
                "%02d Day %02d Hour %02d Minute %02d Second %d Millisecond %d Nanosecond", duration.toDays(),
                duration.toHours() % 24, duration.toMinutes() % 60, duration.toSeconds() % 60,
                duration.toMillis() % 1000, duration.toNanos() % 1000000L);
        System.out.println(formattedElapsedTime);
        // ##############################################################################

        // ####################################Java-9####################################
        formattedElapsedTime = String.format("%02d Day %02d Hour %02d Minute %02d Second %d Millisecond %d Nanosecond",
                duration.toDaysPart(), duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart(),
                duration.toMillisPart(), duration.toNanosPart() % 1000000L);
        System.out.println(formattedElapsedTime);
        // ##############################################################################
    }
}

輸出:

PT3429H21M18.987654321S
142 Day 21 Hour 21 Minute 18 Second 987 Millisecond 654321 Nanosecond
142 Day 21 Hour 21 Minute 18 Second 987 Millisecond 654321 Nanosecond

Trail 了解有關現代日期時間 API 的更多信息:日期時間

暫無
暫無

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

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