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

后端 未结 27 2174
夕颜
夕颜 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:12

    There is a problem. When milliseconds is 59999, actually it is 1 minute but it will be computed as 59 seconds and 999 milliseconds is lost.

    Here is a modified version based on previous answers, which can solve this loss:

    public static String formatTime(long millis) {
        long seconds = Math.round((double) millis / 1000);
        long hours = TimeUnit.SECONDS.toHours(seconds);
        if (hours > 0)
            seconds -= TimeUnit.HOURS.toSeconds(hours);
        long minutes = seconds > 0 ? TimeUnit.SECONDS.toMinutes(seconds) : 0;
        if (minutes > 0)
            seconds -= TimeUnit.MINUTES.toSeconds(minutes);
        return hours > 0 ? String.format("%02d:%02d:%02d", hours, minutes, seconds) : String.format("%02d:%02d", minutes, seconds);
    }
    

提交回复
热议问题