Add hours which are in G:i format php
Question
I currently have a list of time diffs in G:i format.
I would like to add them all up but when i try to it resets at 24 back to 0. How can i get a result like: 54:45 for example?
Thanks in advance.
date_default_timezone_set('UTC');
$username = $row['username'];
$begintime = $row['begintime'];
$endtime = $row['endtime'];
$begintime = new DateTime($begintime);
$begintime = $begintime->format('H:i');
$endtime = new DateTime($endtime);
$endtime = $endtime->format('H:i');
$difference = strtotime($endtime) - strtotime($begintime);
$difference = date('G:i', $total);
$total_hours += $difference;
Solution
Don't use date()
to format absolute times. Since $difference
contains the time difference in seconds, it's just a matter of simple arithmetics:
$hours = floor( $difference / 60 / 60 );
$minutes = ( $difference / 60 ) % 60;
echo "$hours:$minutes";
OTHER TIPS
You can actually "trick" DateTime
into doing absolute times by adding the differences to an arbitrary date:
$foo = new DateTime();
$bar = new DateTime();
foreach ($intervals as $interval) {
$begin = $interval['begin'];
$end = $interval['end'];
$foo->add($begin->diff($end));
}
// Will be the total time of all intervals, as an interval itself
$total = $foo->diff($bar);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow