Java Convert Number of Seconds to Hours Minutes Seconds String

Tags: TimeUtils Seconds to Time String

In this Java tutorial we learn how to convert a number of seconds into a time String contains number of hours, minutes and seconds.

Implement Time Utils Class

First step we create a new Java class named TimeUtils and write a new method named convertSecondsToTime() which one argument is number of seconds and return a String of hours minutes and seconds values.

TimeUtils.java

public class TimeUtils {

    public static String convertSecondsToTime(int numberOfSeconds) {
        int hours = numberOfSeconds / 3600;
        int minutes = (numberOfSeconds % 3600) / 60;
        int seconds = numberOfSeconds % 60;

        String result = String.format("%02d:%02d:%02d", hours, minutes, seconds);
        return result;
    }

}

How to Convert Seconds to Time String in Java

Following Java program we use the TimeUtils class above to convert 3600 seconds to a String of hours minutes and seconds.

SecondToTimeExample1.java

public class SecondToTimeExample1 {

    public static void main(String... args) {
        int numberOfSecond = 3600;
        String time = TimeUtils.convertSecondsToTime(numberOfSecond);

        System.out.println("Number of seconds: " + numberOfSecond);
        System.out.println("Time: " + time);
    }

}
The output as below.
Number of seconds: 3600
Time: 01:00:00

Below is another Java example to convert 10000 seconds to a String.

SecondToTimeExample2.java

public class SecondToTimeExample2 {

    public static void main(String... args) {
        int numberOfSecond = 10000;
        String time = TimeUtils.convertSecondsToTime(numberOfSecond);

        System.out.println("Number of seconds: " + numberOfSecond);
        System.out.println("Time: " + time);
    }

}
The output as below.
Number of seconds: 10000
Time: 02:46:40

Happy Coding 😊