Convert seconds into days, hours, minutes and seconds

后端 未结 24 2526
说谎
说谎 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 17:13

    an extended version of Glavić's excellent solution , having integer validation, solving the 1 s problem, and additional support for years and months, at the expense of being less computer parsing friendly in favor of being more human friendly:

    diff ( $dtT );
        foreach ( array (
                'y' => 'year',
                'm' => 'month',
                'd' => 'day',
                'h' => 'hour',
                'i' => 'minute',
                's' => 'second' 
        ) as $time => $timename ) {
            if ($diff->$time !== 0) {
                $ret .= $diff->$time . ' ' . $timename;
                if ($diff->$time !== 1 && $diff->$time !== -1 ) {
                    $ret .= 's';
                }
                $ret .= ' ';
            }
        }
        return substr ( $ret, 0, - 1 );
    }
    

    var_dump(secondsToHumanReadable(1*60*60*2+1)); -> string(16) "2 hours 1 second"

提交回复
热议问题