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

Have you ever got the difficulty when you want to sum the two time and display its result with format hours:minutes:seconds by using PHP? Well, now you don’t have to worry about it. This following code will give you the solution.

Here is the code:

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
<?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
}
 
?>

Enjoy it and have a nice code!

Share

4,704 viewsPrint This Post Print This Post

Comments

  1. Bagaimana mengetahui code PHP dengan pejumlahan waktu:

    jika pada

    kOLOM 1 KOLOM 2 KOLOM 3 duration
    12:12:20 13:14:29 … : … : … …………..
    hasil dari kolom 3 dan duration nya???

    tks
    Maulana H

  2. Patrick says:

    It is better to use this return statement:

    return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);

    So you will get leading zero’s if needed.

    Patrick

  3. atha says:

    Menyisipkan kodenya di sebelah mana ya pak, saya bingung.

  4. atha says:

    boleh minta contohnya pak? biar bisa di entri di browser. sama databasenya, kalo bisa tlong ya pak. saya butuh sekali.

    • Contoh di atas tidak pakai database. Tinggal create aja sebuah file .php yang baru, lalu copy-kan semua kode di atas ke dalam file .php tersebut, kemudian jalankan seperti biasa dengan browser untuk melihat hasilnya.

  5. Rommel says:

    thanks.. this is exactly what i need, which is by the way i have been working for almost a day now. thanks..

  6. Tinkesh says:

    Thanks A lot … i was struggling since last two days to add two times …. finaly i have got rid ……..thanks again for this posting

  7. Tinkesh says:

    it was exactly what i was looking for……….thank you very much

  8. Dinesh says:

    How to find the average of the sum of time, please share that too.

Trackbacks

  1. [...] 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 [...]

Speak Your Mind

*


*