Java Convert Hours to Readable Time String

Tags: TimeUnit

In this Java tutorial we learn how to convert a number of hours value into a readable time string in format of days and hours in Java programming language.

How to convert number of hours to readable time string

At the first step, we create a new Java class named TimeUtil and implement a static method named getReadableTimeFromHours(long numberOfHours) to convert a number of hours value into readable time String such as “2 days 3 hours” as the following Java code.

TimeUtil.java

import java.util.concurrent.TimeUnit;

public class TimeUtil {

    /**
     * Convert number of hours value to readable time string.
     * Example of readable time String:
     * - 2 days 3 hours
     * - 1 day 10 hours
     * - 5 days 1 hour
     * @param numberOfHours number of hours
     * @return readable time String
     */
    public static String getReadableTimeFromHours(long numberOfHours) {
        long numberOfDays = TimeUnit.HOURS.toDays(numberOfHours);
        numberOfHours -= TimeUnit.DAYS.toHours(numberOfDays);

        StringBuilder stringBuilder = new StringBuilder();

        if(numberOfDays > 0) {
            if(numberOfDays == 1)
                stringBuilder.append(String.format("%d day ", numberOfDays));
            else
                stringBuilder.append(String.format("%d days ", numberOfDays));
        }

        if(numberOfHours > 0) {
            if(numberOfHours == 1)
                stringBuilder.append(String.format("%d hour ", numberOfHours));
            else
                stringBuilder.append(String.format("%d hours ", numberOfHours));
        }

        return stringBuilder.toString();
    }
}

In the following example Java program, we learn how to use the TimeUtil class above to convert specified number of hours to a readable time String.

TimeUtilExample1.java

public class TimeUtilExample1 {
    public static void main(String... args) {
        String string1 = TimeUtil.getReadableTimeFromHours(60);
        String string2 = TimeUtil.getReadableTimeFromHours(30);
        String string3 = TimeUtil.getReadableTimeFromHours(10);
        String string4 = TimeUtil.getReadableTimeFromHours(1);

        System.out.println(string1);
        System.out.println(string2);
        System.out.println(string3);
        System.out.println(string4);
    }
}
The output as below.
2 days 12 hours 
1 day 6 hours 
10 hours 
1 hour

Happy Coding 😊

Java Convert Milliseconds to Readable Time String

Java Convert Seconds to Readable Time String

Java Convert Minutes to Readable Time String