Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate difference between 2 times in hours in PHP

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.

like image 984
Dev Avatar asked Dec 01 '22 19:12

Dev


2 Answers

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;
like image 105
jcsanyi Avatar answered Dec 10 '22 09:12

jcsanyi


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)
like image 28
salathe Avatar answered Dec 10 '22 10:12

salathe