Explain Codes LogoExplain Codes Logo

How to format a duration in java? (e.g format H:MM:SS)

java
prompt-engineering
functions
datetime
Alex KataevbyAlex Kataev·Nov 27, 2024
TLDR
Duration duration = Duration.ofSeconds(3661); String formatted = String.format("%d:%02d:%02d", duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart()); System.out.println(formatted); // 1:01:01, like a secret agent, but with a time travel twist
  • Duration.toHoursPart(), toMinutesPart(), toSecondsPart(): get the duration's hours, minutes, seconds like a time mining operation.
  • String.format(): Injects our findings into an H: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.

int sec = 3661; int hrs = sec / 3600; // Hours: because 3600 seconds make an hour! int mins = (sec % 3600) / 60; // Minutes: Whatever is left from hours, and one minute has 60 seconds. int secs = sec % 60; // Seconds: And finally, whatever is left! String formatted = String.format("%d:%02d:%02d", hrs, mins, secs); System.out.println(formatted); // 1:01:01, Voila!

⚠️ 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.

Duration negDuration = Duration.ofSeconds(-4995); String formattedNeg = String.format("%d:%02d:%02d", Math.abs(negDuration.toHoursPart()), Math.abs(negDuration.toMinutesPart()), Math.abs(negDuration.toSecondsPart())); // Ouch, time does not like to go backwards!

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.

// Create journey period using Joda-Time Period period = new Period(totalMillis); PeriodFormatter formatter = new PeriodFormatterBuilder() .printZeroRarelyLast() .appendHours() .appendSeparator(":") .appendMinutes() .appendSeparator(":") .appendSeconds() .toFormatter(); // Phew, lots of appending, but hey it works! String formatted = formatter.print(period);

🔄 Also, if you need a duration between two LocalDateTime instances:

LocalDateTime start = LocalDateTime.now(); LocalDateTime end = LocalDateTime.now().plusHours(3).plusMinutes(25).plusSeconds(42); Duration between = Duration.between(start, end); // 007 is on a mission. His time to complete it: 3 hours, 25 minutes, and 42 seconds.