- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to convert millisecond to readable string
Let’s say the following is the declaration for milliseconds:
long millis = 5000000;
Now get the hours, minutes and seconds from the milliseconds:
long hours = TimeUnit.MILLISECONDS.toHours(millis); long minutes = TimeUnit.MILLISECONDS.toMinutes(millis) - (hours * 60); long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) - ((hours * 60 * 60) + (minutes * 60));
Use String.format() to convert the above into readable string.
Example
import java.util.concurrent.TimeUnit; public class Demo { public static void main(String[] argv){ long millis = 5000000; long hours = TimeUnit.MILLISECONDS.toHours(millis); long minutes = TimeUnit.MILLISECONDS.toMinutes(millis) - (hours * 60); long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) - ((hours * 60 * 60) + (minutes * 60)); millis = millis - ((hours * 60 * 60 * 1000) + (minutes * 60 * 1000) + (seconds * 1000)); System.out.println(String.format("Hours = %d
Minutes = %d
Seconds = %d
Milliseconds = %d", hours, minutes, seconds, millis)); System.out.println(String.format("%d hr(s) %d min(s) %d sec(s) %d ms", hours, minutes, seconds, millis)); } }
Output
Hours = 1 Minutes = 23 Seconds = 20 Milliseconds = 0 1 hr(s) 23 min(s) 20 sec(s) 0 ms
Advertisements