- How to convert Milliseconds to Minutes and Seconds in Java? TimeUnit Example Tutorial
- 10 Examples of TimeUnit in Java
- Java Program to convert milliseconds to seconds and minutes using TimeUnit
- Important things to learn about TimeUnit
- Convert Milliseconds to Minutes and Seconds in Java 8
- Convert Milliseconds to Minutes and Seconds Using Java 8’s Duration API
- Convert Milliseconds to Minutes and Seconds Using Java 8’s TimeUnit API
- Conclusion
- Related posts:
- Java Program to Convert Milliseconds to Minutes and Seconds
- Example 1: Milliseconds to Seconds/Minutes Using toMinutes() and toSeconds()
- Example 2: Milliseconds to Seconds/Minutes Using Mathematical Formula
- Преобразование миллисекунд в формат «X минут, X секунд» в Java
How to convert Milliseconds to Minutes and Seconds in Java? TimeUnit Example Tutorial
I used to convert milliseconds to seconds in Java by simply dividing it by 1000, and then into minutes by further dividing it by 60, and then hours by even further dividing by 60 and so on. This works but its not the most elegant way to convert millisecond into hours, minutes, seconds or other time unit. JDK comes with a nice utility class called TimeUnit, which as its name suggest, allow you to convert one time unit into other. So if you have milliseconds e.g. execution time of a method and you want to convert into minutes and seconds to improve readability, you can use TimeUnit.toSeconds() and TimeUnit.toMinutes() methods.
It even come with sleep() method which can be used in place of Thread.sleep() method, as its more readable because it tells you exactly how many seconds or minutes thread is going to sleep.
In this tutorial, you will learn how to convert milliseconds to seconds, minutes and other time units in java. btw, the calculation is not accurate, I mean given it return long the fractional part of seconds or minutes will be lost.
10 Examples of TimeUnit in Java
Let’s see a couple of examples of converting between one time unit to other like millisecond to second, minutes to hours, and seconds to minutes in Java using java.util.concurrent.TimeUnit class in Java
long seconds = TimeUnit.MILLISECONDS.toSeconds(50000); // 5 seconds
long minutes = TimeUnit.MILLISECONDS.toMinutes(300000); // 5 minutes
long hours = TimeUnit.MILLISECONDS.toHours(300000); // 0 hours
long days = TimeUnit.MILLISECONDS.toDays(300000); // 0 days
long milliseconds = TimeUnit.MICROSECONDS.toMillis(duration); // 600,000 milliseconds
long seconds = TimeUnit.MICROSECONDS.toSeconds(duration); // 600 seconds
long minutes = TimeUnit.MICROSECONDS.toMinutes(duration); // 10 minutes
int hours = TimeUnit.MICROSECONDS.toHours(duration); // 0 hours
Java Program to convert milliseconds to seconds and minutes using TimeUnit
Here is complete Java Program to cover millisecond values to second, minute and hour in Java using TimeUnit class. Bottom line is you should use TimeUnit to convert Milliseconds to minutes and seconds
package dto; import java.util.concurrent.TimeUnit; /** * Java Program to demonstrate how to use TimeUnit class to * convert millisecond and microsecond to seconds, minutes * hours and days in Java. * * @author WINDOWS 11 * */ public class TimeUnitDemo < public static void main(String args[])< long milliseconds = 500*1000; long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds); // 500 seconds long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds); // 8 minutes long hours = TimeUnit.MILLISECONDS.toHours(milliseconds); // 0 hours long days = TimeUnit.MILLISECONDS.toDays(milliseconds); // 0 days System.out.println("milliseconds : " + milliseconds); System.out.println("converted to seconds : " + seconds); System.out.println("converted to minutes: " + minutes); System.out.println("converted to hours: " + hours); System.out.println("converted to days: " + days); long duration = 600*1000*1000; milliseconds = TimeUnit.MICROSECONDS.toMillis(duration); // 600,000 milliseconds seconds = TimeUnit.MICROSECONDS.toSeconds(duration); // 600 seconds minutes = TimeUnit.MICROSECONDS.toMinutes(duration); // 10 minutes hours = TimeUnit.MICROSECONDS.toHours(duration); // 0 hours days = TimeUnit.MICROSECONDS.toDays(duration); // 0 days System.out.println("micro seconds : " + duration); System.out.println("converted to milliseconds : " + milliseconds); System.out.println("converted to seconds : " + seconds); System.out.println("converted to minutes: " + minutes); System.out.println("converted to hours: " + hours); System.out.println("converted to days: " + days); > >
milliseconds : 500000 converted to seconds : 500 converted to minutes: 8 converted to hours: 0 converted to days: 0 micro seconds : 600000000 converted to milliseconds : 600000 converted to seconds : 600 converted to minutes: 10 converted to hours: 0 converted to days: 0
Important things to learn about TimeUnit
Here are a couple of importnat points about TimeUnit class in Java which I think every Java developer should know and remember:
3) TimeUnit supports many units e.g. nano seconds, micro seconds, milliseconds, seconds, minutes, hours and days.
That’s all about how to convert millisecond to seconds, minutes and hours in Java. This is the most elegant way to convert one time unit into another. You don’t need to maintain conversion factor. It’s also less error prone as it reduce typing error. You can also use TimeUnit for timed wait, timed join and alternative of sleep method.
Convert Milliseconds to Minutes and Seconds in Java 8
In Java programming, one of the common task is to convert milliseconds to minutes and seconds. In this article, we will explore how to achieve this conversion using Java 8 features.
Prerequisites: To follow along with the examples in this article, you will need a basic understanding of Java programming and familiarity with Java 8’s Date and Time API.
Convert Milliseconds to Minutes and Seconds Using Java 8’s Duration API
Step 1: Getting the Milliseconds Input:
First, we need to get the number of milliseconds as input from the user or any other data source. For the sake of simplicity, let’s assume we have a long variable named milliseconds that holds the value of milliseconds.
Step 2: Conversion Duration API:
Java 8 introduced the Duration class, which provides convenient methods for working with time intervals. To convert milliseconds to minutes and seconds, we can create a Duration object using the milliseconds and then extract the minutes and seconds components.
// Convert milliseconds to Duration Duration duration = Duration.ofMillis(milliseconds); // Extract minutes and seconds from Duration long minutes = duration.toMinutes(); long seconds = duration.getSeconds() % 60;
Step 3: Displaying the Result: Once we have the minutes and seconds values, we can display them to the user or use them in further calculations. Here’s an example of how to display the converted values:
System.out.println("Converted Time:"); System.out.println("Minutes: " + minutes); System.out.println("Seconds: " + seconds);
Example Usage: Let’s put it all together in a complete example:
import java.time.Duration; public class MillisecondsToMinutesSecondsConverter < public static void main(String[] args) < long milliseconds = 1234567; // Example milliseconds value // Convert milliseconds to Duration Duration duration = Duration.ofMillis(milliseconds); // Extract minutes and seconds from Duration long minutes = duration.toMinutes(); long seconds = duration.getSeconds() % 60; // Display the converted time System.out.println("Converted Time:"); System.out.println("Minutes: " + minutes); System.out.println("Seconds: " + seconds); >>
Converted Time: Minutes: 20 Seconds: 34
Convert Milliseconds to Minutes and Seconds Using Java 8’s TimeUnit API
The TimeUnit class provides useful methods for time-related conversions. Here’s an alternative approach using TimeUnit:
import java.util.concurrent.TimeUnit; public class MillisecondsToMinutesSecondsConverter < public static void main(String[] args) < long milliseconds = 1234567; // Example milliseconds value // Convert milliseconds to minutes and seconds long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds); long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds) % 60; // Display the converted time System.out.println("Converted Time:"); System.out.println("Minutes: " + minutes); System.out.println("Seconds: " + seconds); >>
Converted Time: Minutes: 20 Seconds: 34
In this approach, we use the TimeUnit.MILLISECONDS.toMinutes(milliseconds) method to convert the milliseconds directly to minutes. Similarly, TimeUnit.MILLISECONDS.toSeconds(milliseconds) is used to convert the milliseconds to seconds. The % 60 operation is applied to calculate the remaining seconds after converting to minutes.
Conclusion
Both approaches achieve the same result, and you can choose the one that suits your coding style or specific requirements.
Related posts:
Java Program to Convert Milliseconds to Minutes and Seconds
To understand this example, you should have the knowledge of the following Java programming topics:
In Java, we can use the built-in methods:
- toMinutes() — to convert milliseconds to minutes
- toSeconds() — to convert milliseconds to seconds
Example 1: Milliseconds to Seconds/Minutes Using toMinutes() and toSeconds()
import java.util.concurrent.TimeUnit; class Main < public static void main(String[] args) < long milliseconds = 1000000; // us of toSeconds() // to convert milliseconds to minutes long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds); System.out.println(milliseconds + " Milliseconds = " + seconds + " Seconds"); // use of toMinutes() // to convert milliseconds to minutes long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds); System.out.println(milliseconds + " Milliseconds = " + minutes + " Minutes"); >>
1000000 Milliseconds = 1000 Seconds Or 1000000 Milliseconds = 16 Minutes
In the above program, we have used the long datatype to store milliseconds , minutes , and seconds values. It is because the toMinutes() and toSeconds() methods return values in long .
Note: To use the methods, we must import the java.util.concurrent.TimeUnit package.
We can also use the basic mathematical formulas to convert milliseconds to minutes and seconds.
// convert milliseconds to seconds Seconds = milliseconds / 1000 // convert seconds to minutes minutes = seconds / 60 // convert millisecons to minutes minutes = (milliseconds / 1000) / 60
Example 2: Milliseconds to Seconds/Minutes Using Mathematical Formula
1000000 Milliseconds = 1000 Seconds 1000000 Milliseconds = 16 Minutes
In the above program, we have
- converted milliseconds to seconds by dividing it by 1000
- converted to minutes by dividing the seconds by 60
Преобразование миллисекунд в формат «X минут, X секунд» в Java
Часто в процессе разработки программ на языке Java возникает задача измерения времени выполнения определенных операций. Для этого обычно используется метод System.currentTimeMillis() , который возвращает текущее время в миллисекундах. Однако полученное значение не всегда удобно для восприятия: миллисекунды сложно перевести в более привычные минуты и секунды.
Допустим, есть программа, которая регистрирует время начала выполнения операции и время окончания. По итогу надо вывести потраченное время в формате «ХХ минут, ХХ секунд». Как это можно реализовать?
Сначала нужно получить разность между временем окончания и временем начала операции – это и будет количество потраченных миллисекунд. После этого, исходя из того, что одна секунда равна 1000 миллисекундам, а одна минута равна 60 секундам, можно получить количество минут и секунд.
long startTime = System.currentTimeMillis(); // выполнение операции long endTime = System.currentTimeMillis(); long elapsedTime = endTime - startTime; // время в миллисекундах long seconds = (elapsedTime / 1000) % 60; long minutes = (elapsedTime / (1000 * 60)) % 60;
Теперь полученные значения можно использовать для формирования строки, которую можно вывести пользователю. Для форматирования строки можно воспользоваться методом String.format() .
String time = String.format("%d минут, %d секунд", minutes, seconds); System.out.println(time);
Таким образом, преобразование миллисекунд в минуты и секунды в Java можно выполнить при помощи простых математических операций и метода форматирования строк. Это позволяет выводить время, затраченное на выполнение операций, в более понятном для пользователя формате.