How to format a duration in java? (e.g format H:MM:SS)
Duration.toHoursPart()
,toMinutesPart()
,toSecondsPart()
: get the duration's hours, minutes, seconds like a time mining operation.String.format()
: Injects our findings into anH:MM:SS
pattern, like time's enigma machine.- Output: Our time code unraveled in
H:MM:SS
format. Neat, right?
In-depth duration formatting
💡 Here's the breakdown of String.format()
: it uses placeholders following a special syntax. For instance, %d
represents a decimal integer while %02d
ensures the integer always takes up 2 spaces, adding a zero if needed.
Pre-Java 8: Simple Arithmetic Approach
Pre- java.time.Duration
era (pre-Java 8), we can still format duration using arithmetic operations.
⚠️ Don't let integer division fool you, it truncates the decimal part. So, watch for potential pitfalls here!
Java 8 and beyond: Unleashing Duration class
In Java 8+, you have the java.time.Duration
at your disposal. It's capable of representing time-based duration with precision and convenience.
Going beyond: Advanced tips and tricks
Negative durations? No problem! Apply Math.abs()
before formatting. Your users will thank you.
If you need more control over duration representation, let's say eliminating zero quantities, you can choose to employ a DateTimeFormatter
or Joda-Time.
For those Joda-Time enthusiasts
📘 Joda-Time still shines in the face of Java 8+, especially when PeriodFormatter
is needed for custom duration formatting.
🔄 Also, if you need a duration between two LocalDateTime
instances:
Was this article helpful?