Convert seconds into days, hours, minutes and seconds

后端 未结 24 2628
说谎
说谎 2020-11-22 16:30

I would like to convert a variable $uptime which is seconds, into days, hours, minutes and seconds.

Example:



        
24条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 16:47

    Although it is quite old question - one may find these useful (not written to be fast):

    function d_h_m_s__string1($seconds)
    {
        $ret = '';
        $divs = array(86400, 3600, 60, 1);
    
        for ($d = 0; $d < 4; $d++)
        {
            $q = (int)($seconds / $divs[$d]);
            $r = $seconds % $divs[$d];
            $ret .= sprintf("%d%s", $q, substr('dhms', $d, 1));
            $seconds = $r;
        }
    
        return $ret;
    }
    
    function d_h_m_s__string2($seconds)
    {
        if ($seconds == 0) return '0s';
    
        $can_print = false; // to skip 0d, 0d0m ....
        $ret = '';
        $divs = array(86400, 3600, 60, 1);
    
        for ($d = 0; $d < 4; $d++)
        {
            $q = (int)($seconds / $divs[$d]);
            $r = $seconds % $divs[$d];
            if ($q != 0) $can_print = true;
            if ($can_print) $ret .= sprintf("%d%s", $q, substr('dhms', $d, 1));
            $seconds = $r;
        }
    
        return $ret;
    }
    
    function d_h_m_s__array($seconds)
    {
        $ret = array();
    
        $divs = array(86400, 3600, 60, 1);
    
        for ($d = 0; $d < 4; $d++)
        {
            $q = $seconds / $divs[$d];
            $r = $seconds % $divs[$d];
            $ret[substr('dhms', $d, 1)] = $q;
    
            $seconds = $r;
        }
    
        return $ret;
    }
    
    echo d_h_m_s__string1(0*86400+21*3600+57*60+13) . "\n";
    echo d_h_m_s__string2(0*86400+21*3600+57*60+13) . "\n";
    
    $ret = d_h_m_s__array(9*86400+21*3600+57*60+13);
    printf("%dd%dh%dm%ds\n", $ret['d'], $ret['h'], $ret['m'], $ret['s']);
    

    result:

    0d21h57m13s
    21h57m13s
    9d21h57m13s
    

提交回复
热议问题