In this article, we will see how to format Java’s duration object in a readable format.

Java’s duration class is part of the java.time package and is often used for measuring time intervals or durations in various Java applications. While it’s efficient for calculations, its default string representation is not very user-friendly.

We can create a custom method that converts Java’s duration object into a more human-readable format. We can implement this custom method by extracting the hours, minutes, and seconds and formatting them accordingly.

Following is an example:

import java.time.Duration;

public class DurationPrettyPrintingExample {

    public static String prettyPrintDuration(Duration duration) {
        long hours = duration.toHours();
        long minutes = duration.minusHours(hours).toMinutes();
        long seconds = duration.minusHours(hours).minusMinutes(minutes).getSeconds();

        return String.format("%d hours, %d minutes, %d seconds", hours, minutes, seconds);
    }

    public static void main(String[] args) {
        Duration duration = Duration.ofHours(2).plusMinutes(30).plusSeconds(15);
        String prettyDuration = prettyPrintDuration(duration);

        System.out.println("Pretty Printed Duration: " + prettyDuration);
    }
}

In the above example, the prettyPrintDuration method calculates the hours, minutes, and seconds from the duration and formats them into a human-readable string.

Categorized in:

Tagged in: