Explain Codes LogoExplain Codes Logo

How to convert Milliseconds to "X mins, x seconds" in Java?

java
prompt-engineering
best-practices
mathematical-operations
Nikita BarsukovbyNikita Barsukov·Nov 9, 2024
TLDR

For on-the-go devs looking to convert milliseconds to "X mins, X seconds", here's a handy snippet:

long millis = // throw in your milliseconds here long mins = TimeUnit.MILLISECONDS.toMinutes(millis); // Minutes mind blown by TimeUnit in 3..2..1.. long secs = TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(mins); // Early bird catches the seconds String formatted = String.format("%d mins, %02d seconds", mins, secs); // Nice and clean System.out.println(formatted); // Surprise! Time just got a facelift.

Just tweak millis with your millisecond value and voilà - you've translated a gargantuan millisecond value into a crisp, human-friendly format.

Watch out for quirky moments

Despite our immediate success, it's always wise to watch for the uncalled guests in our code. Here are some things to consider:

  • Large numbers vs math's wrath: Always use long to avoid nasty overflows.

  • Negative Nancy: Any negative value would wreak havoc in your beautiful script. An IllegalArgumentException is good weapon to bring to this fight:

    if (millis < 0) { throw new IllegalArgumentException("Duration can't go back to the future!"); }
  • When minutes and seconds just won't cut it: Going beyond hours? No worries: extend the solution.

    long hours = TimeUnit.MILLISECONDS.toHours(millis); mins = mins - TimeUnit.HOURS.toMinutes(hours); // Gotcha! // Process as before...
  • In the prehistoric era (too much legacy code), TimeUnit's methods might not be available. Stick to manual mathematical operations then:

    long mins = (millis / (1000*60)) % 60; long secs = (millis / 1000) % 60;
  • Zeroes can be heroes. Use String.format() to maintain leading zeroes and make things a lot prettier:

    String formatted = String.format("%02d mins, %02d seconds", mins, secs);

If TimeUnits don't make sense

Sometimes TimeUnits are just too high-tech. If you want to do the good old mathematical way:

long mins = (millis / (1000 * 60)) % 60; // Math to the rescue! long secs = (millis / 1000) % 60; // More math! String formatted = String.format("%02d mins, %02d seconds", mins, secs); // Good old formatting

Fancy formatting

Here's how to deal with those who fancy more flavours in their script. Using a StringBuilder:

StringBuilder timeString = new StringBuilder(); long days = TimeUnit.MILLISECONDS.toDays(millis); millis -= TimeUnit.DAYS.toMillis(days); long hours = TimeUnit.MILLISECONDS.toHours(millis); millis -= TimeUnit.HOURS.toMillis(hours); mins = TimeUnit.MILLISECONDS.toMinutes(millis); millis -= TimeUnit.MINUTES.toMillis(mins); secs = TimeUnit.MILLISECONDS.toSeconds(millis); if (days > 0) { timeString.append(days).append(" Days "); // Oh! Look a day passed! } if (hours > 0) { timeString.append(hours).append(" Hours "); // Another hour! Time flies, doesn't it? } timeString.append(mins).append(" Minutes ").append(secs).append(" Seconds"); System.out.println(timeString.toString()); // Print and see time fly!

Timekeeping: The Modern Way

With Java 8, the java.time package gives us a refined approach for dealing with time durations:

Instant start = Instant.now(); // Ready, Steady... // ... time-consuming operations ... Instant end = Instant.now(); // Stop! Its End-Time. Duration duration = Duration.between(start, end); // Time just traveled from start to end. long seconds = duration.getSeconds(); long absSeconds = Math.abs(seconds); String positive = String.format( "PT%dM%dS", absSeconds / 60, absSeconds % 60); // Bingo! You got the precise duration. System.out.println(positive); // PT1M35S

The java.time.Duration offers between which is a nice way to measure the duration from one instant to another.