Search code examples
bashtime

How can I convert milliseconds to time and not date?


Let's say I have millisecond=169920 which equals 00:02:49.92 (h:m:s:ms). This input is coming from a text file, one below the other.

How I can convert these miliseconds to time in Bash?

Most questions ask about milliseconds to dates or use epoch time that is not relevant here: I only need time, not date.

example of the text file with miliseconds:

cat milisecond.txt
169920
269320
163920
1339520

Solution

  • How to convert milliseconds to hours, minutes, seconds and milliseconds with bash and % (modulo operation)?

    millisecs="169920"
    
    h="$((millisecs/3600000))"
    m="$(((millisecs%3600000)/60000))"
    s="$(((millisecs%60000)/1000))"
    ms="$((millisecs%1000))"
    
    printf "%02d:%02d:%02d.%03d\n" "$h" "$m" "$s" "$ms"
    

    Output:

    00:02:49.920