Java Programming
Time Conversion
Milliseconds
Coding Tutorials
Programming Tips

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

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Converting milliseconds to a more readable format like "minutes and seconds" is a common requirement in programming, especially when dealing with time intervals, animation durations, or event timings in applications. Java, with its rich API, provides various ways to handle such conversions efficiently.

Understanding Milliseconds

Milliseconds represent the thousandth part of a second. To convert them into minutes and seconds, we need to understand the basic time conversions:

  • 1 second = 1000 milliseconds
  • 1 minute = 60 seconds = 60,000 milliseconds

Using Basic Arithmetic

A straightforward way to convert milliseconds into minutes and seconds involves using simple arithmetic operations—division and modulus.

  1. Extract Minutes: Use division to find out how many whole minutes fit into the given milliseconds.
  2. Extract Seconds: Use the modulus operator to find out what remains after extracting minutes, then convert this remainder into seconds.

Here's a simple example in Java to demonstrate this method:

java
1public class TimeConverter {
2    public static String convertMillisToMinSec(long millis) {
3        long minutes = millis / 60000;  // 60000 milliseconds in a minute
4        long seconds = (millis % 60000) / 1000;   // remaining milliseconds converted to seconds
5
6        return minutes + " mins, " + seconds + " seconds";
7    }
8
9    public static void main(String[] args) {
10        long milliseconds = 123456;
11        System.out.println(convertMillisToMinSec(milliseconds));  // Output: 2 mins, 3 seconds
12    }
13}

This function directly computes minutes and seconds from the total milliseconds, providing a clear, concise conversion. It's efficient and straightforward, suitable for many applications requiring basic time formatting.

Using java.time Package

For more complex time manipulations, Java 8 introduced the java.time package, which offers a modern approach to date and time. You can use this API for precise time calculations and formatting.

To convert milliseconds to minutes and seconds using java.time, you can use the following steps:

  1. Create a Duration Instance: Construct a Duration object from the milliseconds.
  2. Extract Units: Use the methods toMinutes() and toSecondsPart() to get the minute and second components.

Here's how you can utilize the java.time API:

java
1import java.time.Duration;
2
3public class TimeFormatter {
4    public static String formatMillis(long millis) {
5        Duration duration = Duration.ofMillis(millis);
6        long minutes = duration.toMinutes();
7        int seconds = duration.toSecondsPart();
8
9        return minutes + " mins, " + seconds + " seconds";
10    }
11
12    public static void main(String[] args) {
13        long milliseconds = 987654;
14        System.out.println(formatMillis(milliseconds));  // Output: 16 mins, 27 seconds
15    }
16}

Comparing Both Methods

Both methods are effective, but the choice between them depends on your specific needs—simplicity versus precision and additional functionality.

MethodProsCons
Basic ArithmeticSimple and straightforwardLimited to basic calculations
java.time APIMore precise and flexibleSlightly more complex, requires Java 8 or higher

Additional Considerations

When converting time, consider the edge cases and precision requirements of your application. For example, handle cases where milliseconds are less than 1000 (all result in 0 mins, <1 sec), and ensure your application's performance when dealing with a large number of conversions.

Conclusion

Converting milliseconds to minutes and seconds in Java can be achieved through basic arithmetic for most needs or using the powerful java.time API for more complex scenarios. Choosing the right method depends on your application's requirements in terms of readability, ease of use, and the features offered by your Java version.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.