How to convert Milliseconds to "X mins, x seconds" in Java?
For on-the-go devs looking to convert milliseconds to "X mins, X seconds", here's a handy snippet:
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
longto avoid nasty overflows. -
Negative Nancy: Any negative value would wreak havoc in your beautiful script. An
IllegalArgumentExceptionis good weapon to bring to this fight: -
When minutes and seconds just won't cut it: Going beyond hours? No worries: extend the solution.
-
In the prehistoric era (too much legacy code),
TimeUnit's methods might not be available. Stick to manual mathematical operations then: -
Zeroes can be heroes. Use
String.format()to maintain leading zeroes and make things a lot prettier:
If TimeUnits don't make sense
Sometimes TimeUnits are just too high-tech. If you want to do the good old mathematical way:
Fancy formatting
Here's how to deal with those who fancy more flavours in their script. Using a StringBuilder:
Timekeeping: The Modern Way
With Java 8, the java.time package gives us a refined approach for dealing with time durations:
The java.time.Duration offers between which is a nice way to measure the duration from one instant to another.
Was this article helpful?