How to format a duration in java? e.g format HMMSS
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Formatting a duration in Java to display in the format of H:MM:SS can be achieved using a variety of techniques and classes. Java provides several ways to handle durations, particularly given enhancements in newer versions. This article will guide you through different methods to format a duration, take you through the classes involved, and provide useful examples to make the process straightforward.
Understanding Duration in Java
In Java, the Duration class from the java.time package is a key component for representing amounts of time. It models a duration amount of time measured in seconds and nanoseconds. This class is part of the Java 8 and later Date-Time API and offers methods both to manipulate duration instances and to convert them to various units.
Key Methods of the Duration Class
between(Temporal startInclusive, Temporal endExclusive): Obtains aDurationrepresenting the duration between two temporal objects.ofHours(long hours),ofMinutes(long minutes),ofSeconds(long seconds), etc.: Factory methods that create aDurationinstance.toDays(),toHours(),toMinutes(),toMillis(), etc.: Conversion methods to return the duration in other units.
Formatting a Duration in H:MM:SS
To format a Duration in H:MM:SS, you first need to extract the relevant hours, minutes, and seconds. This can be done with conventional arithmetic operations, given that Duration.toMillis() provides the total milliseconds. Here's a step-by-step guide to formatting:
Example: Formatting Using Duration
Explanation
- Calculating Total Seconds:
duration.getSeconds()is used to obtain the full duration in seconds. - Extracting Hours: Integer division of the total seconds by 3600 gives the count of hours.
- Extracting Minutes: Modulo division by 3600 gives remaining seconds; dividing by 60 derives whole minutes.
- Extracting Remaining Seconds: Modulo division by 60 gives the remaining seconds.
- Formatting String:
String.format("%d:%02d:%02d", ...);constructs the final time string with zero-padded two-digit minutes and seconds.
Additional Techniques for Duration Formatting
Using Java 8 and Later Streams
Java Streams can also construct formatted duration strings, enhancing readability:
toMinutesPart() and toSecondsPart() methods are available in Java 9 and later, simplifying zero-padding calculations.
Using ChronoUnit for Operations
ChronoUnit offers another layer to perform unit-specific operations, beneficial for understanding large intervals:
This calculation doesn't materially improve performance but showcases Java's support for intuitive, temporal arithmetic.
Key Points Summary
| Feature | Description |
| Duration Class | Represents time-based amounts in seconds and nanoseconds. |
| Factory Methods | Create Duration instances like ofHours, ofMinutes, ofSeconds. |
| Conversion Methods | Convert Duration to other units like days, hours, minutes. |
| Custom Formatter | Manual calculation and String.format to achieve H:MM:SS. |
| Java 9 Updates | Use toMinutesPart() & toSecondsPart() for simpler zero-padded values. |
| ChronoUnit Utility | Helpful for conceptual operations on time units. |
Java's extensive libraries and classes make formatting durations both simple and versatile. Whether through tedious arithmetic or succinct stream operations, developers have varied tools at their disposal to present time efficiently in their applications.
Related reading
- How to format a Java string with leading zero?
- How to format date and time in Android?
- How to format Joda-Time DateTime to only mm/dd/yyyy?
- How to format strings in Java
- How to free memory in Java?
- How to generate a ddl creation script with a modern Spring Boot Data JPA and Hibernate setup?
- How to generate a random permutation in Java
- How to generate a secure random alphanumeric string in Java efficiently?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.