How to convert Milliseconds to "X mins, x seconds" in Java?
To convert milliseconds to "X mins, X seconds" in Java, you can use the TimeUnit
class from the java.util.concurrent
package.
Here is an example of how you can do this:
import java.util.concurrent.TimeUnit;
long millis = 1234567;
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(minutes);
System.out.printf("%d mins, %d seconds", minutes, seconds);
This will output the following:
20 mins, 43 seconds
Alternatively, you can use the Duration
class from the java.time
package to convert milliseconds to a Duration
object, and then use the toMinutes
and getSeconds
methods to obtain the minutes and seconds.
Here is an example of how you can do this:
import java.time.Duration;
long millis = 1234567;
Duration duration = Duration.ofMillis(millis);
long minutes = duration.toMinutes();
long seconds = duration.getSeconds() - TimeUnit.MINUTES.toSeconds(minutes);
System.out.printf("%d mins, %d seconds", minutes, seconds);
This will also output the following:
20 mins, 43 seconds