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!

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
@Maulana Hasanudin
Apakah seperti ini yang Anda maksud?
How to Calculate The Sum and Duration of Two Different Time Using PHP.
It is better to use this return statement:
So you will get leading zero’s if needed.
Patrick
Hi Patrick,
Thanks for your kindly feedback. Just updated the post.
Menyisipkan kodenya di sebelah mana ya pak, saya bingung.
Sesuaikan saja dengan kebutuhan di kode Anda. Kode yang di atas itu hanya contoh sederhana saja. Selamat mengeksplorasi!
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.
thanks.. this is exactly what i need, which is by the way i have been working for almost a day now. thanks..
You’re welcome. Glad it is useful for you.
Thanks A lot … i was struggling since last two days to add two times …. finaly i have got rid ……..thanks again for this posting
You are very welcome. Glad to hear good news from you.
it was exactly what i was looking for……….thank you very much
How to find the average of the sum of time, please share that too.
Can you explain it in more detail, what do you mean by average of the sum time. Do you have the special formula to implement it?
Yes.
For example, we have five time in the format hours:minutes, i want to sum those five times and calculate the average of time and display it in hours:minutes format.