get time difference in hours minutes and seconds

2019-08-27 22:07发布

问题:

I have two dates,

$expiry_time = strtotime('comming from database');
$current_date = strtotime(date('Y-m-d H:i:s'));
$time_diff = ($expiry_time-$current_date)/(3600);

Here, $time_diff will give me difference in hours. eg. 5.67. But, I want it in hours, minute and second format. How can I achieve this? Thanks.

回答1:

Use DateTime() with DateInterval()

$expiry_time = new DateTime($row['fromdb']);
$current_date = new DateTime();
$diff = $expiry_time->diff($current_time);
echo $diff->format('%H:%I:%S');


回答2:

use the date() function.

$time_diff = $expiry_time - $current_date;
echo date('H:i:s', $time_diff);


回答3:

http://php.net/manual/fr/function.date-diff.php has a bunch of useful stuf to do this operation as well



回答4:

You should use the DateTime class but if you use PHP version older than 5.2 you can do it like that:

function convert_time_by_seconds($interval) {
    if($interval < 0) {
        return false;
    }
    $seconds_n_miliseconds = explode('.', $interval);
    $interval = $seconds_n_miliseconds[0];

    $hours = floor($interval / (60*60));
    $minutes = floor(($interval - ($hours*60*60)) / 60);
    $seconds = floor(($interval - ($hours*60*60)) - ($minutes*60));
    $ms = empty($seconds_n_miliseconds[1]) ? 0 : $seconds_n_miliseconds[1];
    return array('h' => $hours, 'm' => $minutes, 's' => $seconds, 'ms' => $ms);
}

$time_diff = time() - strtotime('2014-07-17 14:23:51');
$result = convert_time_by_seconds($time_diff);
var_dump($result);