How to Calculate The Sum and Duration of Two Different Time Using PHP

There was a question that asked to me about how to sum and find out the duration of the two different time using PHP code regarding this my article. So, this following code will answer the question. You will be able to know how to calculate the sum and duration between two different time.

Here is the answer!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
 
/**
 * @author Masino Sinaga, http://www.openscriptsolution.com
 * @copyright August 23, 2010
 */
 
$time1 = '12:12:20';
$time2 = '13:14:29';
echo 'Begin of Time: '.$time1;
echo '<br />End of Time: '.$time2;
echo '<br />The Sum of Time: '. sum_the_time($time1, $time2);  // this will give you a result: 19:12:25
echo '<br />Duration: '. duration_time($time1, $time2); // this will give you a result: 0 Day(s), 1 Hour(s), 2 Minute(s), 9 Second(s).
 
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); 
}
 
function duration_time($parambegindate, $paramenddate) {
  $begindate = strtotime($parambegindate);
  $enddate = strtotime($paramenddate);
  $diff = intval($enddate) - intval($begindate);                 
  $diffday = intval(floor($diff/86400));
  $modday = ($diff%86400);
  $diffhour = intval(floor($modday/3600));
  $diffminute = intval(floor(($modday%3600)/60));
  $diffsecond = ($modday%60);
  return round($diffday)." Day(s), ".round($diffhour)." Hour(s), ".round($diffminute,0)." Minute(s), ".round($diffsecond,0)." Second(s).";
}
 
?>

If you run that code, then it will output to your browser as following:

Begin of Time: 12:12:20
End of Time: 13:14:29
The Sum of Time: 25:26:49
Duration: 0 Day(s), 1 Hour(s), 2 Minute(s), 9 Second(s).
Share

1,277 viewsPrint This Post Print This Post

Comments

  1. Arlia Widy says:

    $diffday = intval(floor($diff/86400));

    how about month and year ?
    where did 86400 come from?

  2. Great post! 86400 came from the following: 24 hours x 60 minutes x 60 seconds = 86400 seconds in 1 day

Speak Your Mind

*


*