Calculate difference between 2 times in hours in PHP

34,816

Solution 1

Convert them both to timestamp values, and then subtract to get the difference in seconds.

$ts1 = strtotime(str_replace('/', '-', '02/01/2013 08:24'));
$ts2 = strtotime(str_replace('/', '-', '31/12/2012 13:46'));
$diff = abs($ts1 - $ts2) / 3600;

Solution 2

Another way is to use PHP's date-related classes. The example below uses DateTime::diff() to get a DateInterval object ($interval). It then uses the interval's properties to arrive at the total number of hours in the interval.

$a = DateTime::createFromFormat('H:i d/m/Y', '08:24 02/01/2013');
$b = DateTime::createFromFormat('H:i d/m/Y', '13:46 31/12/2012');

$interval = $a->diff($b);
$hours    = ($interval->days * 24) + $interval->h
          + ($interval->i / 60) + ($interval->s / 3600);

var_dump($hours); // float(42.633333333333)

Solution 3

I got a simple solution, Try this one -

echo getTimeDiff("10:30","11:10");

function getTimeDiff($dtime,$atime)
    {
        $nextDay = $dtime>$atime?1:0;
        $dep = explode(':',$dtime);
        $arr = explode(':',$atime);
        $diff = abs(mktime($dep[0],$dep[1],0,date('n'),date('j'),date('y'))-mktime($arr[0],$arr[1],0,date('n'),date('j')+$nextDay,date('y')));
        $hours = floor($diff/(60*60));
        $mins = floor(($diff-($hours*60*60))/(60));
        $secs = floor(($diff-(($hours*60*60)+($mins*60))));
        if(strlen($hours)<2){$hours="0".$hours;}
        if(strlen($mins)<2){$mins="0".$mins;}
        if(strlen($secs)<2){$secs="0".$secs;}
        return $hours.':'.$mins.':'.$secs;
    }

Solution 4

If you have the dates as timestamps (use strtotime if needed), then just subtract them, optionally take the absolute value, then divide to 3600 (number of seconds in an hour). Easy ^_^

Share:
34,816
Deval Khandelwal
Author by

Deval Khandelwal

node.js mostly

Updated on July 11, 2022

Comments

  • Deval Khandelwal
    Deval Khandelwal almost 2 years

    I have two times - For eg- the current time - 08:24 and date is 02/01/2013 in dd/mm/yyyy format and I have another time at 13:46 and date is 31/12/2012 . So, how can I calculate the difference between the 2 times in hours using PHP. (i.e. 42.63 hours) Thanks in advance.

  • jcsanyi
    jcsanyi almost 11 years
    Edited: strtotime parses as m/d/y or d-m-y, so converted / to - before parsing
  • Bhavik Joshi
    Bhavik Joshi about 9 years
    it gives the difference but its doesn't give me whether the difference is positive or negative
  • jcsanyi
    jcsanyi about 9 years
    You can just remove the abs() call if you need preserve the sign of the difference. ($ts1 - $ts2) / 3600
  • Bhavik Joshi
    Bhavik Joshi about 9 years
    yeah it was my mistake i didnt noticed that