Convert seconds to hours, minutes, seconds

前端 未结 13 1003
梦谈多话
梦谈多话 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:49

    Simple one-liner

    $ secs=236521
    $ printf '%dh:%dm:%ds\n' $(($secs/3600)) $(($secs%3600/60)) $(($secs%60))
    65h:42m:1s
    

    With leading zeroes

    $ secs=236521
    $ printf '%02dh:%02dm:%02ds\n' $(($secs/3600)) $(($secs%3600/60)) $(($secs%60))
    65h:42m:01s
    

    With days

    $ secs=236521
    $ printf '%dd:%dh:%dm:%ds\n' $(($secs/86400)) $(($secs%86400/3600)) $(($secs%3600/60)) \
      $(($secs%60))
    2d:17h:42m:1s
    

    With nanoseconds

    $ secs=21218.6474912
    $ printf '%02dh:%02dm:%02fs\n' $(echo -e "$secs/3600\n$secs%3600/60\n$secs%60"| bc | xargs echo)
    05h:53m:38.647491s
    

    Based on https://stackoverflow.com/a/28451379/188159 but edit got rejected.

提交回复
热议问题