RNK
RNK

Reputation: 5792

get time difference in hours minutes and seconds

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.

Upvotes: 0

Views: 7870

Answers (4)

John Conde
John Conde

Reputation: 219794

Use DateTime() with DateInterval()

$expiry_time = new DateTime($row['fromdb']);
$current_date = new DateTime();
$diff = $expiry_time->diff($current_date);
echo $diff->format('%H:%I:%S');  // returns difference in hr min and sec

Upvotes: 7

Samuil Banti
Samuil Banti

Reputation: 1795

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);

Upvotes: 3

Arnaud Bouchot
Arnaud Bouchot

Reputation: 1993

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

Upvotes: 1

Zombiesplat
Zombiesplat

Reputation: 953

use the date() function.

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

Upvotes: 0

Related Questions