Convert number of seconds into HH:MM (without seconds) in Java

前端 未结 3 608
囚心锁ツ
囚心锁ツ 2020-12-20 08:16

I\'m aware that you can use DateUtils.formatElapsedTime(seconds) to convert a number of seconds into a String with the format HH:MM:SS

3条回答
  •  甜味超标
    2020-12-20 08:44

    MadProgrammer has already provided a good Java 8 answer (which will work in Java 6 and 7 too when you use the ThreeTen Backport). In Java 9 still a bit more of the calculation can be done in the library:

        int seconds = 3665;
        Duration dur = Duration.ofSeconds(seconds);
        String formatted = String.format("%d:%02d", dur.toHours(), dur.toMinutesPart());
        System.out.println(formatted);
    

    Output:

    1:01

    The toMinutesPart method and other toXxxPart methods were introduced in Java 9.

提交回复
热议问题