Scott M. Mcdermott

UNIX Systems & Network Administrator
available for contract or salaried positions

time_t_to_readable

#
# Takes a given time_t string and returns a human readable
# time representation of the interval length
#

source ~/lib/sh/include

require fsetvar
require freturn

time_t_to_readable ()
{
        local +i strtime=$1
        local +i divset
        local +i unit
        local +i lastunit
        local +i threshold1

        local -i time
        local -i divisor
        local -i threshold
        local -i thisdivisor
        local -i dividend
        local -i remainder

        if [[ ${strtime:0:1} == '-' ]]; then
                local -i negative
                strtime=${strtime:1}
        elif [[ ${strtime:0:1} == '+' ]]; then
                unset negative
                strtime=${strtime:1}
        fi

        [[ $strtime =~ ^[0]*(.*) ]]
        time=${BASH_REMATCH[1]}

        # otherwise we end up getting divisions by zero if we break early
        divisor=1
        lastdivisor=1

        # unit:threshold,divisor
        for divset in s:99,1 m:99,60 h:72,60 d:90,24 M:36,30; do
                unit=${divset%:*}
                threshold1=${divset#?:}
                threshold=${threshold1%,*}
                thisdivisor=${divset#*,}
                divisor=$((divisor * thisdivisor))
                dividend=$((time / divisor))
                remainder=$((time % divisor))
                ((dividend < threshold)) && break
                lastdivisor=$divisor
                lastunit=$unit
        done

        left=$((remainder / lastdivisor))
        #left=${left%0*}
        [[ ${negative+unset} ]] && let dividend=-dividend
        printf                                                  \
                -v printline                                    \
                "%2d:%02d%c%c" $dividend $left $unit            \
                #${lastunit:-$unit}

        freturn "$printline"
}
# vim:syn=sh:ft=sh