获得毫秒格式

时间:2011-08-13 06:29:16

标签: java android string format milliseconds

我试图让这个字符串返回Minute:Second:Millisecond for MediaPlayer。我找到了这段代码,但无法弄清楚如何使毫秒工作并将其放在2位小数。我确信这对合适的人来说很简单!

private String getTimeString(long millis) {
        StringBuffer buf = new StringBuffer();

        int hours = (int) (millis / (1000*60*60));
        int minutes = (int) (( millis % (1000*60*60) ) / (1000*60));
        int seconds = (int) (( ( millis % (1000*60*60) ) % (1000*60) ) / 1000);


        buf
            .append(String.format("%02d", hours))
            .append(":")
            .append(String.format("%02d", minutes))
            .append(":")
            .append(String.format("%02d", seconds));


        return buf.toString();
    }

总是谢谢你们

3 个答案:

答案 0 :(得分:7)

一秒钟内有1000毫秒,即毫秒需要3位小数:

/** return time in format 1:23.456 */
private String getTimeString(long millis) {
    int minutes = (int) (millis / (1000 * 60));
    int seconds = (int) ((millis / 1000) % 60);
    int milliseconds = (int) (millis % 1000);
    String.format("%d:%02d.%03d", minutes, seconds, milliseconds);
}

如果你绝对想要2位数毫秒,你实际上得到1/100秒而不是毫秒:

/** return time in format 1:23.45 */
private String getTimeString(long millis) {
    int minutes = (int) (millis / (1000 * 60));
    int seconds = (int) ((millis / 1000) % 60);
    int seconds100 = (int) ((millis / 10) % 100);
    String.format("%d:%02d.%02d", minutes, seconds, seconds100);
}

但是,媒体播放器的常见显示格式是使用一位数字,持续10秒:

/** return time in format 1:23.4 */
private String getTimeString(long millis) {
    int minutes = (int) (millis / (1000 * 60));
    int seconds = (int) ((millis / 1000) % 60);
    int seconds10 = (int) ((millis / 100) % 10);
    String.format("%d:%02d.%d", minutes, seconds, seconds10);
}

答案 1 :(得分:1)

试试这个:

private String getTimeString(long millis) {
    long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
    long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) -
                   TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
    millis -= TimeUnit.MINUTES.toMillis(minutes) + TimeUnit.SECONDS.toMillis(seconds);

    return String.format("%d:%d:%d", minutes, seconds, millis);
}

答案 2 :(得分:0)

如果你想把毫秒放在两个小数位,请记住你只能显示10ms的增量; 1ms = 0.001s,小数点后三位。但无论如何,您正在寻找的代码是:

int rem_milliseconds = (int)(millis % 1000); // Remaining ms after last second
...
.append(String.format("%02d", rem_milliseconds));

我把它留在小数点后2位。