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

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

问题描述

我正在制作一个秒表,我正在使用Java的SimpleDateFormat将毫秒数转换为漂亮的hh:mm:ss:SSS格式。问题是小时字段总是有一些随机数。这是我正在使用的代码:

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天全站免登陆