获取人类可读的时间(以纳秒为单位) [英] Get Human readable time from nanoseconds

查看:143
本文介绍了获取人类可读的时间(以纳秒为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 System.nanoTime()

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

Long remainingTime = allTimeForDownloading - elapsedTime;

但是我无法弄清楚如何获得人类可以理解的纳秒级形式。例如: 1d 1h 36s 3m 50s

But I cannot figure how to get a human readable form of the nanoseconds; for example: 1d 1h, 36s and 3m 50s.

我该怎么办?

推荐答案

如果 remainingTime nanoseconds 为单位,只需进行数学运算并将值附加到 StringBuilder

If remainingTime is in nanoseconds, just do the math and append the values to a 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);
    }
}

上面的输出是:


1h 23m 43s 23402000ns

1h 23m 43s 23402000ns

(1小时23分钟,43秒和23402000纳秒)。

(1 hour, 23 minutes, 43 seconds and 23402000 nanoseconds).

这篇关于获取人类可读的时间(以纳秒为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆