How to convert milliseconds to human readable hours, minutes, seconds and milliseconds in Java

2 Answers

0 votes
import java.time.Duration;

public class Program {
    public static void main(String[] args) {
        int ms = 317520;
        Duration duration = Duration.ofMillis(ms);
        
        String result = String.format("%02dh:%02dm:%02ds:%03dms",
                duration.toHours(),
                duration.toMinutesPart(),
                duration.toSecondsPart(),
                duration.toMillisPart());
        
        System.out.println(result);
    }
}




/*
run:

00h:05m:17s:520ms
  
*/


 



answered Jun 26, 2024 by avibootz
0 votes
public class Program {
    public static void main(String[] args) {
        int ms = 317520;

        int hours = (int) ((ms / (1000 * 60 * 60)) % 24);
        int minutes = (int) ((ms / (1000 * 60)) % 60); 
        int seconds = (int) (ms / 1000) % 60;
        int milliseconds = ms - ((hours * 3600000) + (minutes * 60000) + (seconds * 1000));
        
        System.out.println(hours + ":h " + minutes + ":m " + seconds + ":s " + milliseconds + "ms");
    }
}




/*
run:

0:h 5:m 17:s 520ms
  
*/


 



answered Jun 26, 2024 by avibootz
...