Here's a quick solution that utilizes SimpleDateFormat to convert milliseconds:
long ms = YOUR_MILLIS; // Don't forget to replace this with your actual millisecondsString time = new SimpleDateFormat("HH:mm:ss").format(new Date(ms - TimeZone.getDefault().getRawOffset()));
// Bravo, time is now in "hh:mm:ss"
Note: make sure to subtract your timezone offset to display the accurate UTC time.
Breaking down the TimeUnit approach
Java's TimeUnit class lets you convert different units of time easily and concisely:
long milliseconds = 123456789; // Fantastic arbitrary number// Hours - Spoiler Alert: It run in circles every 24 hourslong hours = TimeUnit.MILLISECONDS.toHours(milliseconds);
long remainingMsAfterHours = milliseconds - TimeUnit.HOURS.toMillis(hours);
// Minutes - Because being precisely on time is overratedlong minutes = TimeUnit.MILLISECONDS.toMinutes(remainingMsAfterHours);
long remainingMsAfterMinutes = remainingMsAfterMinutes - TimeUnit.MINUTES.toMillis(minutes);
// Seconds - for all our fellow procrastinators out therefinallong seconds = TimeUnit.MILLISECONDS.toSeconds(remainingMsAfterMinutes) - (minutes * 60);
// Time's ready, serve hot!String formattedTime = String.format("%02d:%02d:%02d", hours, minutes, seconds);
We use String.format to keep those leading zeroes in the "hh:mm:ss" format, because we like things neat, don't we?
Converting time the java.time way
Java 8 gifted us java.time, a more dependable way to handle time:
**Fraction of seconds support? ** Check! Extremely helpful in high-precision circumstances.
Validate your masterpiece
Test your method against a spattering of scenarios because that's what robust code is all about:
long[] testMillis = {0, 1000, 123450, 3600000, 86399999}; // Check all: Zero, One-liners, Textwalls, and Full-length novelsfor (long millis : testMillis) {
System.out.println(formatMillisToHHMMSS(millis)); // Print and admire your handywork}
This validation ensures your ultimate solution runs smoothly for all milliseconds!
A solution for every time (pun intended)
For the ones using older Java versions, never fear, SimpleDateFormat is here:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // Don't confuse the computer with different timezonesString formatted = sdf.format(new Date(milliseconds));
Remember: It's important to set the timezone to UTC to avoid nasty local offsets.
explain-codes/Java/How to convert milliseconds to "hh:mm:ss" format?