How to convert Milliseconds to “X mins, x seconds” in Java?

后端 未结 27 1833
夕颜
夕颜 2020-11-22 03:59

I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current Syste

27条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 04:11

    This is easier in Java 9:

        Duration elapsedTime = Duration.ofMillis(millisDiff );
        String humanReadableElapsedTime = String.format(
                "%d hours, %d mins, %d seconds",
                elapsedTime.toHours(),
                elapsedTime.toMinutesPart(),
                elapsedTime.toSecondsPart());
    

    This produces a string like 0 hours, 39 mins, 9 seconds.

    If you want to round to whole seconds before formatting:

        elapsedTime = elapsedTime.plusMillis(500).truncatedTo(ChronoUnit.SECONDS);
    

    To leave out the hours if they are 0:

        long hours = elapsedTime.toHours();
        String humanReadableElapsedTime;
        if (hours == 0) {
            humanReadableElapsedTime = String.format(
                    "%d mins, %d seconds",
                    elapsedTime.toMinutesPart(),
                    elapsedTime.toSecondsPart());
    
        } else {
            humanReadableElapsedTime = String.format(
                    "%d hours, %d mins, %d seconds",
                    hours,
                    elapsedTime.toMinutesPart(),
                    elapsedTime.toSecondsPart());
        }
    

    Now we can have for example 39 mins, 9 seconds.

    To print minutes and seconds with leading zero to make them always two digits, just insert 02 into the relevant format specifiers, thus:

        String humanReadableElapsedTime = String.format(
                "%d hours, %02d mins, %02d seconds",
                elapsedTime.toHours(),
                elapsedTime.toMinutesPart(),
                elapsedTime.toSecondsPart());
    

    Now we can have for example 0 hours, 39 mins, 09 seconds.

提交回复
热议问题