Calculate the difference between 2 times in hours in PHP

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

+4
source share
5 answers

Convert both of them to timestamp values, and then subtract them 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; 
+4
source

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

 $a = DateTime::createFromFormat('H:id/m/Y', '08:24 02/01/2013'); $b = DateTime::createFromFormat('H:id/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) 
+4
source

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

+1
source

I have a simple solution, try this -

 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; } 
+1
source

I think the following code is useful to get an idea on how to calculate the time difference using PHP

 function date_diff($date_1 , $date_2 , $format) { $datetime1 = date_create($date_1); $datetime2 = date_create($date_2); $diff = date_diff($datetime1, $datetime2); return $diff->format($format); } 

The above function is useful for calculating the difference between two moments and dates. Dates are given as arguments with the output format.

The output format is shown below:

// '% y Year% m Month% d Day% h Hours% i Minute% s Seconds => 1 year 3 Month 14 day 11 hours 49 minutes 36 seconds //'% y Year% m Month% d Day '=> 1 year 3 months 14 days // '% m Month% d Day' => 3 Month 14 day // '% d Day% h Clock' => 14 day 11 hours // '% d Day' => 14 days / / '% h Hours% i Minute% s Seconds => 11 hours 49 minutes 36 seconds //'% i Minute% s Seconds' => 49 minutes 36 seconds // '% h Clock => 11 hours //'% a Days

0
source

Source: https://habr.com/ru/post/1484002/


All Articles