- Convert Milliseconds into Days, Hours, Minutes, Seconds in Java
- How to convert milliseconds into hours and days in Java?
- Method 1: Simple Conversion
- Method 2: Using Java’s built-in TimeUnit class
- Method 3: Using Joda-Time library
- Java миллисекунды в часы
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Работа с миллисекундами в формате даты и времени в Java
- Проблема
- Решение
Convert Milliseconds into Days, Hours, Minutes, Seconds in Java
Basically when you want to check the exact time taken to execute a program then you may need to calculate the time. So in this case you get the start time in milliseconds and end time in milliseconds and you want to check how much time that program took to execute. Therefore you would like to convert the milliseconds into minutes and seconds to make it more readable format because millisecond unit may not be so understandable quickly.
Lets see the below example, it will provide you better idea to convert the milliseconds into days or hours or minutes or seconds.
Formula to convert Milliseconds into Days, Hours, Minutes, Seconds in Java:
seconds = MilliSeconds / 1000;
minutes = seconds / 60;
hours = minutes / 60;
days = hours / 24;
import java.util.concurrent.TimeUnit; public class MillisToDayHrMinSec public static void main(String[] args) final long milliseconds = 5478965412358l; final long day = TimeUnit.MILLISECONDS.toDays(milliseconds); final long hours = TimeUnit.MILLISECONDS.toHours(milliseconds) - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(milliseconds)); final long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliseconds)); final long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds)); final long ms = TimeUnit.MILLISECONDS.toMillis(milliseconds) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(milliseconds)); System.out.println("milliseconds :-" + milliseconds); System.out.println(String.format("%d Days %d Hours %d Minutes %d Seconds %d Milliseconds", day, hours, minutes, seconds, ms)); > >
Output :
———————
milliseconds :-5478965412358
63413 Days 22 Hours 50 Minutes 12 Seconds 358 Milliseconds
Hope you like this simple example for time conversion, where we are converting milliseconds into days or hours or minutes or seconds. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.
How to convert milliseconds into hours and days in Java?
When working with time values in Java, it is common to use the millisecond representation of time, since it provides a convenient way to represent a specific point in time as a numerical value. However, sometimes it is necessary to display the time in a more human-readable format, such as hours or days. This can be achieved by converting the number of milliseconds into hours or days, taking into account the conversion factors for each unit of time.
Method 1: Simple Conversion
To convert milliseconds into hours and days using simple conversion in Java, you can follow these steps:
- First, get the milliseconds value that you want to convert.
- Then, convert the milliseconds into seconds by dividing it by 1000.
- Next, convert the seconds into minutes by dividing it by 60.
- After that, convert the minutes into hours by dividing it by 60.
- Finally, convert the hours into days by dividing it by 24.
Here is the Java code that implements the above steps:
long milliseconds = 86400000; // 1 day in milliseconds long seconds = milliseconds / 1000; long minutes = seconds / 60; long hours = minutes / 60; long days = hours / 24; System.out.println("Milliseconds: " + milliseconds); System.out.println("Seconds: " + seconds); System.out.println("Minutes: " + minutes); System.out.println("Hours: " + hours); System.out.println("Days: " + days);
Milliseconds: 86400000 Seconds: 86400 Minutes: 1440 Hours: 24 Days: 1
In the above code, we have initialized the milliseconds variable with the value of 1 day in milliseconds. Then, we have divided it by 1000 to get the seconds value, by 60 to get the minutes value, by 60 again to get the hours value, and by 24 to get the days value. Finally, we have printed all the converted values using the System.out.println() method.
You can use the above code as a reference to convert any milliseconds value into hours and days using simple conversion in Java.
Method 2: Using Java’s built-in TimeUnit class
To convert milliseconds into hours and days using Java’s built-in TimeUnit class, you can follow these steps:
- First, you need to create a long variable to store the milliseconds value that you want to convert. Let’s call it «milliseconds».
long milliseconds = 86400000; // 1 day in milliseconds
- Next, you can use the TimeUnit class to convert the milliseconds value into hours and days. The TimeUnit class provides several methods for this purpose, such as «convert», «toDays», and «toHours».
long hours = TimeUnit.MILLISECONDS.toHours(milliseconds); long days = TimeUnit.MILLISECONDS.toDays(milliseconds);
In this example, we are using the «toHours» and «toDays» methods to convert the «milliseconds» value into hours and days, respectively.
System.out.println("Milliseconds: " + milliseconds); System.out.println("Hours: " + hours); System.out.println("Days: " + days);
Here’s the complete code example:
import java.util.concurrent.TimeUnit; public class MillisecondsToHoursAndDays public static void main(String[] args) long milliseconds = 86400000; // 1 day in milliseconds long hours = TimeUnit.MILLISECONDS.toHours(milliseconds); long days = TimeUnit.MILLISECONDS.toDays(milliseconds); System.out.println("Milliseconds: " + milliseconds); System.out.println("Hours: " + hours); System.out.println("Days: " + days); > >
Milliseconds: 86400000 Hours: 24 Days: 1
In this example, we have successfully converted the given milliseconds value into hours and days using Java’s built-in TimeUnit class.
Method 3: Using Joda-Time library
To convert milliseconds into hours and days using Joda-Time library, you can follow the steps below:
- First, you need to add the Joda-Time library to your project. You can do this by adding the following dependency to your project’s pom.xml file:
dependency> groupId>joda-timegroupId> artifactId>joda-timeartifactId> version>2.10.10version> dependency>
- Next, you can create a Duration object using the milliseconds value. This can be done using the Duration.millis() method as shown below:
long milliseconds = 86400000; // 1 day in milliseconds Duration duration = Duration.millis(milliseconds);
- To convert the duration into hours, you can use the Duration.getStandardHours() method as shown below:
long hours = duration.getStandardHours();
- Similarly, to convert the duration into days, you can use the Duration.getStandardDays() method as shown below:
long days = duration.getStandardDays();
import org.joda.time.Duration; public class MillisecondsConverter public static void main(String[] args) long milliseconds = 86400000; // 1 day in milliseconds Duration duration = Duration.millis(milliseconds); long hours = duration.getStandardHours(); long days = duration.getStandardDays(); System.out.println("Milliseconds: " + milliseconds); System.out.println("Hours: " + hours); System.out.println("Days: " + days); > >
Milliseconds: 86400000 Hours: 24 Days: 1
That’s it! You have successfully converted milliseconds into hours and days using Joda-Time library.
Java миллисекунды в часы
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Работа с миллисекундами в формате даты и времени в Java
Возможность точного измерения времени до миллисекунд важна для многих приложений, начиная от научных экспериментов и заканчивая играми и мультимедиа.
Возможность точного измерения времени до миллисекунд важна для многих приложений, начиная от научных экспериментов и заканчивая играми и мультимедиа. Но как получить такую точность в Java?
Проблема
Представьте, что у вас есть код, который извлекает текущее время и возвращает его в формате «YYYY-MM-DD HH:MM:SS», то есть до секунд. Например:
public static String getCurrentTimeStamp()
Это отлично работает, если вам нужна точность только до секунд. Но что, если вам нужно еще точнее, до миллисекунд? В таком случае, вы хотели бы получить время в формате «YYYY-MM-DD HH:MM:SS.MS», где «MS» — это миллисекунды.
Решение
Для решения этой проблемы вам необходимо немного изменить формат, используемый в вашем SimpleDateFormat. Вместо «yyyy-MM-dd HH:mm:ss» вы должны использовать «yyyy-MM-dd HH:mm:ss.SSS». Это укажет SimpleDateFormat, что вы хотите включить миллисекунды в выводимую строку. Итак, исправленный код будет выглядеть так:
public static String getCurrentTimeStamp()
Теперь, когда вы вызываете этот метод, он вернет текущее время до миллисекунд, например, «2022-01-01 12:00:00.123».
Таким образом, работа с миллисекундами в Java может быть достаточно простой, если вы знаете, как правильно настроить SimpleDateFormat.