php timestamp difference in hours code example

Example 1: php time difference in hours

date_default_timezone_set("Africa/Johannesburg");
    $now = new DateTime();
    $future_date = new DateTime('2020-10-21 00:00:00');
    
    $interval = $future_date->diff($now);
    
    echo ($interval->format("%a") * 24) + $interval->format("%h"). " hours". $interval->format(" %i minutes ");
    print_r($now->format('Y-m-d H:i:s'));

Example 2: difference between two timestamps php

$datetime1 = new DateTime('2016-11-30 03:55:06');//start time
$datetime2 = new DateTime('2016-11-30 11:55:06');//end time
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y years %m months %d days %H hours %i minutes %s seconds');//00 years 0 months 0 days 08 hours 0 minutes 0 seconds

Tags:

Php Example