2011-08-13 99 views
0

我想讓這個字符串返回Minute:Second:Millisecond for my MediaPlayer。我已經找到這個代碼,但不知道如何使毫秒工作,並把它放在小數點後兩位。我相信它對於合適的人來說簡單!獲取毫秒格式

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(); 
    } 

感謝你們總是

+0

也許你應該看看[Formatter](http://download.oracle.com/javase/1.5.0/docs/api /java/util/Formatter.html)? – kylc

回答

6

有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); 
} 

然而,一個普通的顯示器媒體播放器的格式是使用一個十位秒的數字:

/** 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); 
} 
0

如果你想把毫秒的兩位小數,請記住,你只能夠顯示的10ms的增量; 1ms = 0.001s,小數點後三位。但無論如何,您正在尋找的代碼是:

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

我把它留在小數點後兩位。

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); 
}