Java Program to convert millisecond to readable string

Java 8Object Oriented ProgrammingProgramming

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\nMinutes = %d\nSeconds = %d\nMilliseconds =
         %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
raja
Published on 25-Apr-2019 15:49:05
Advertisements