栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 将字节大小和毫秒转换为人类易于理解的单位

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 将字节大小和毫秒转换为人类易于理解的单位

public static void main(String[] args) {
    System.out.println(getSecondDescription(864));
    System.out.println(getSecondDescription(9640));
    System.out.println(getSecondDescription(3600000 * 2));
    System.out.println(getSecondDescription(96400000));


    System.out.println(getBytesSizeDescription(1024 * 16L));
    System.out.println(getBytesSizeDescription(1024L * 1024L * 16L));
    System.out.println(getBytesSizeDescription(1024L * 1024L * 1024L * 16L));
    System.out.println(getBytesSizeDescription(1024L * 1024L * 1024L * 1024L * 16L));
    System.out.println(getBytesSizeDescription(1024L * 1024L * 1024L * 1024L * 1024L * 16L));
}


//region TODO:将字节大小转换为人类易于理解的单位


private static long half_rounded(long x) {
    return (x + (x < 0 ? -1 : 1)) / 2;
}

public static String getBytesSizeDescription(long size) {
    final long limit = 10 * 1024;
    final long limit2 = limit * 2 - 1;

    if (Math.abs(size) < limit) {
        return String.format("%d bytes", size);
    } else {
        size /= (1 << 9);        
        if (Math.abs(size) < limit2) {
            return String.format("%d kB", half_rounded(size));
        } else {
            size /= (1 << 10);
            if (Math.abs(size) < limit2) {
                return String.format("%d MB", half_rounded(size));
            } else {
                size /= (1 << 10);
                if (Math.abs(size) < limit2)
                    return String.format("%d GB", half_rounded(size));
                else {
                    size /= (1 << 10);
                    return String.format("%d TB", half_rounded(size));
                }
            }
        }
    }
}
//endregion

//region TODO:将毫秒转换为人类易于理解的单位
public static String getSecondDescription(double elapsed_msec) {
    double seconds;
    double minutes;
    double hours;
    double days;


    if (elapsed_msec < 1000.0)
        return String.format("%.3f ms", elapsed_msec / 1000f);

    seconds = elapsed_msec / 1000.0;
    minutes = Math.floor(seconds / 60.0);
    seconds -= 60.0 * minutes;
    if (minutes < 60.0)
        return String.format("%02d:%06.3f", (int) minutes, seconds);

    hours = Math.floor(minutes / 60.0);
    minutes -= 60.0 * hours;
    if (hours < 24.0)
        return String.format("%02d:%02d:%06.3f", (int) hours, (int) minutes, seconds);

    days = Math.floor(hours / 24.0);
    hours -= 24.0 * days;
    return String.format("%.0f d %02d:%02d:%06.3f", days, (int) hours, (int) minutes, seconds);
}
//endregion
输出
0.864 ms
00:09.640
02:00:00.000
1 d 02:46:40.000


16 kB
16 MB
16 GB
16 TB
16384 TB
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1014819.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号