0

how can I get difference between 2 time in hours. For ex:

$data1 = '2018-04-24 02:30:00';
$date2 = now();

how to get diff between $date1 and $date2.

EDIT: code posted by OP in comments

<?php //date_default_timezone_set('UTC+6'); 
$time1 = strtotime('2018-04-25 12:00:00'); 
$time2 = time(); 
echo $time2.'<br>'; 
echo date('Y-m-d h:i:s', $time2).'<br>'; 
echo ($time1-$time2)/3600; ?>
Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
Tahmidur Rahman
  • 304
  • 1
  • 4
  • 14

2 Answers2

1
<?php

$datetime1 = new DateTime('2018-04-24 02:30:00');
$datetime2 = new DateTime(date('Y-m-d H:i:s'));
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y %m %d %H:%I:%S');

The result will be:

00 0 1 08:06:15

00 --> years
0  --> months
1  --> days 
08 --> hours
06 --> minutes
15 --> seconds

You can modify it as you like but i suggest you keep at least days cause the hours may differ by a few hours but the days can differ by many days.

pr1nc3
  • 8,108
  • 3
  • 23
  • 36
0
$data1 = '2018-04-24 02:30:00';
$data2 = date('y-m-d H:i:s');

$formated_in = date('Y-m-d H:i:s', strtotime($data1));
$formated_out = date('Y-m-d H:i:s', strtotime($data2));

$formated_new_in = strtotime($formated_in);
$formated_new_out = strtotime($formated_out);

$sub_total = $formated_new_out - $formated_new_in;
$sub_total = gmdate("H:i", $sub_total);
echo $sub_total;
Sachin Aghera
  • 486
  • 3
  • 8