Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A "time of day" is not the same thing as a "duration of time". It doesn't makes sense to add together two time of day values - regardless of platform or language. Think about it - what does "11:00 PM" + "4:00 AM" equal? It's a nonsensical question.</p> <p>You should be thinking about PHP's <a href="http://php.net/manual/en/class.dateinterval.php" rel="nofollow"><code>DateInterval</code></a> class, not the <code>DateTime</code> class.</p> <p>It should be noted that if you follow the examples on the dup posts of using <code>strtotime</code> it will work only when each individual input, and the final result, are all under 24 hours. Why? Because that's the maximum amount of time allowed in a standard day. That's the consequence of mixing "time of day" with "duration of time".</p> <p>This should work for you:</p> <pre><code>function time_to_interval($time) { $parts = explode(':',$time); return new DateInterval('PT'.$parts[0].'H'.$parts[1].'M'.$parts[2].'S'); } function add_intervals($a,$b) { $zerodate = new DateTime('0000-01-01 00:00:00'); $dt = clone $zerodate; $dt-&gt;add($a); $dt-&gt;add($b); return $zerodate-&gt;diff($dt); } function format_interval_hhmmss($interval){ $totalhours = $interval-&gt;h + ($interval-&gt;d * 24); return $totalhours.$interval-&gt;format(':%I:%S'); } $interval1 = time_to_interval('01:04:00'); $interval2 = time_to_interval('00:13:22'); $interval3 = add_intervals($interval1,$interval2); echo format_interval_hhmmss($interval3); </code></pre> <p>Note that the choice of value for <code>$zerodate</code> isn't really all that important. It's just that <em>some</em> reference point is required, since PHP doesn't provide operations directly on <code>DateInterval</code>.</p> <p>Also note that the the <code>DateInterval::format</code> function doesn't have a formatter to get you total number of hours inclusive of days, so if there's any chance the total could be 24 hours or more, then you have to format that part yourself, like I showed in the <code>format_interval_hhmmss</code> function.</p> <p>Also note that my PHP skills are not all that great, so there may be a more efficient way to write these functions.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload