如何在 Java 中以 hh:mm:ss.SSS 格式格式化经过的时间间隔? [英] How to format an elapsed time interval in hh:mm:ss.SSS format in Java?

查看:13
本文介绍了如何在 Java 中以 hh:mm:ss.SSS 格式格式化经过的时间间隔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作秒表,我使用 Java 的 SimpleDateFormat 将毫秒数转换为不错的hh:mm:ss:SSS"格式.问题是 hours 字段中总是有一些随机数.这是我正在使用的代码:

I'm making a stop watch where I'm using Java's SimpleDateFormat to convert the number of milliseconds into a nice "hh:mm:ss:SSS" format. The problem is the hours field always has some random number in it. Here's the code I'm using:

public static String formatTime(long millis) {
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss.SSS");

    String strDate = sdf.format(millis);
    return strDate;
}

如果我去掉 hh 部分,那么它工作正常.否则在 hh 部分,即使传入的参数(毫秒数)为零,它也会显示诸如07"之类的随机内容.

If I take off the hh part then it works fine. Otherwise in the hh part it'll display something random like "07" even if the argument passed in (number of milliseconds) is zero.

虽然我不太了解 SimpleDateFormat 类.感谢您的帮助.

I don't know much about the SimpleDateFormat class though. Thanks for any help.

推荐答案

这是我如何做到的,只使用标准的 JDK(这可以追溯到 Java 1.1,通过更改 StringBuilder回到StringBuffer):

Here's how I've done it, using only the standard JDK (this will work as far back as Java 1.1 by changing StringBuilder back to StringBuffer):

static public String formatMillis(long val) {
    StringBuilder                       buf=new StringBuilder(20);
    String                              sgn="";

    if(val<0) { sgn="-"; val=Math.abs(val); }

    append(buf,sgn,0,(val/3600000)); val%=3600000;
    append(buf,":",2,(val/  60000)); val%=  60000;
    append(buf,":",2,(val/   1000)); val%=   1000;
    append(buf,".",3,(val        ));
    return buf.toString();
    }

/** Append a right-aligned and zero-padded numeric value to a `StringBuilder`. */
static private void append(StringBuilder tgt, String pfx, int dgt, long val) {
    tgt.append(pfx);
    if(dgt>1) {
        int pad=(dgt-1);
        for(long xa=val; xa>9 && pad>0; xa/=10) { pad--;           }
        for(int  xa=0;   xa<pad;        xa++  ) { tgt.append('0'); }
        }
    tgt.append(val);
    }

这篇关于如何在 Java 中以 hh:mm:ss.SSS 格式格式化经过的时间间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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