bashshell

Convert seconds to hours, minutes, seconds


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:05

Solution

  • I use the following function myself:

    function show_time () {
        num=$1
        min=0
        hour=0
        day=0
        if((num>59));then
            ((sec=num%60))
            ((num=num/60))
            if((num>59));then
                ((min=num%60))
                ((num=num/60))
                if((num>23));then
                    ((hour=num%24))
                    ((day=num/24))
                else
                    ((hour=num))
                fi
            else
                ((min=num))
            fi
        else
            ((sec=num))
        fi
        echo "$day"d "$hour"h "$min"m "$sec"s
    }
    

    Note it counts days as well. Also, it shows a different result for your last number.