Convert seconds to hours, minutes, seconds

前端 未结 13 1001
梦谈多话
梦谈多话 2020-12-02 14:08

How can I convert seconds to hours, minutes and seconds?

show_time() {
  ?????
}

show_time 36 # 00:00:36
show_time 1036 # 00:17:26
show_time 91925 # 25:32:0         


        
13条回答
  •  攒了一身酷
    2020-12-02 14:58

    For us lazy people: ready-made script available at https://github.com/k0smik0/FaCRI/blob/master/fbcmd/bin/displaytime :

    #!/bin/bash
    
    function displaytime {
      local T=$1
      local D=$((T/60/60/24))
      local H=$((T/60/60%24))
      local M=$((T/60%60))
      local S=$((T%60))
      [[ $D > 0 ]] && printf '%d days ' $D
      [[ $H > 0 ]] && printf '%d hours ' $H
      [[ $M > 0 ]] && printf '%d minutes ' $M
      [[ $D > 0 || $H > 0 || $M > 0 ]] && printf 'and '
      printf '%d seconds\n' $S
    }
    
    displaytime $1
    

    Basically just another spin on the other solutions, but has the added bonus of suppressing empty time units (f.e. 10 seconds instead of 0 hours 0 minutes 10 seconds). Couldn't quite track down the original source of the function, occurs in multiple git repos..

提交回复
热议问题