Question

I am trying to find time differences between two times. This is the code I have:

$ddtcounter1="2014-03-06 20:20:30";

$ddtcounter2="2014-03-07 21:20:30";

$today = new DateTime($ddtcounter2);
$pastDate = $today->diff(new DateTime($ddtcounter1));

$total= $pastDate->h . ".";
$total2=$total.$pastDate->i;

echo $total2; //echo the time difference in hour.minutes form (Exmple:2.1)

How can I find the time differences? I have read few guides and tutorials and they didn't help. I read a lot of answers but they didn't work for me...

EDIT: Example (For who didn't understand the question):

First time: 2014-03-06 20:30:30

second is: 2014-03-07 19:30:30

The time difference will be 23.0 (23 hours), because it happened 1 day earlier!

Was it helpful?

Solution

This should work:

$ddtcounter1="2014-03-06 20:15:30";
$ddtcounter2="2014-03-07 21:20:30";

$date1 = new DateTime($ddtcounter1);
$date2 = new DateTime($ddtcounter2);
$diff = $date1->diff($date2);

$hours = $diff->d * 24;
$hours += $diff->h;
echo $hours;
echo $diff->i; // Minutes
echo sprintf('%s.%s', $hours, $diff->i); // Hours.Minutes
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top