Getting millisecond format

梦想的初衷 提交于 2019-12-07 17:39:26

There are 1000 milliseconds in one second, i.e. you'd need 3 decimal places for the milliseconds:

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

If you absolutely want 2 digits for milliseconds, you actually get 1/100 seconds and not milliseconds:

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

However, a common display format for media players is to use one digit for 10ths of seconds:

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

Try this:

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

If you want to put the milliseconds at two decimal places, keep in mind that you will only be able to show increments of 10ms; 1ms = 0.001s, three decimal places. But regardless, the code you are looking for is:

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

I left it at 2 decimal places.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!