Sum Time with Format hh:mm:ss by Using PHP

<?php

/**
 * @author Masino Sinaga, http://www.openscriptsolution.com
 * @copyright October 13, 2009
 */

echo sum_the_time('01:45:22', '17:27:03');  // this will give you a result: 19:12:25

function sum_the_time($time1, $time2) {
  $times = array($time1, $time2);
  $seconds = 0;
  foreach ($times as $time)
  {
    list($hour,$minute,$second) = explode(':', $time);
    $seconds += $hour*3600;
    $seconds += $minute*60;
    $seconds += $second;
  }
  $hours = floor($seconds/3600);
  $seconds -= $hours*3600;
  $minutes  = floor($seconds/60);
  $seconds -= $minutes*60;
  // return "{$hours}:{$minutes}:{$seconds}";
  return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds); // Thanks to Patrick
}

?>
Advertisements

4 thoughts on “Sum Time with Format hh:mm:ss by Using PHP

  1. //in case anyone need to substract

    function sub_the_time($time1, $time2) {
    $seconds = 0;
    $seconds1 = 0;
    $seconds2 = 0;

    list($hour,$minute,$second) = explode(‘:’, $time1);
    $seconds1 += $hour*3600;
    $seconds1 += $minute*60;
    $seconds1 += $second;

    list($hour,$minute,$second) = explode(‘:’, $time2);
    $seconds2 += $hour*3600;
    $seconds2 += $minute*60;
    $seconds2 += $second;

    if ($seconds1 >= $seconds2) { $seconds = $seconds1 – $seconds2;}

    if ($seconds1 < $seconds2) { $seconds = (24*3600) + $seconds1 – $seconds2;}

    $hours = floor($seconds/3600);
    $seconds -= $hours*3600;
    $minutes = floor($seconds/60);
    $seconds -= $minutes*60;
    // return "{$hours}:{$minutes}:{$seconds}";
    return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
    }

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s