Bagaimana Menghitung Jumlah dan Selisih Dua Waktu yang Berbeda Menggunakan PHP

Ada sebuah pertanyaan yang diajukan kepada saya mengenai bagaimana menjumlahkan dan mengetahui durasi dari dua buah waktu yang berbeda menggunakan kode PHP terkait dengan salah satu dari artikel saya. Baiklah, kode berikut akan menjawab pertanyaan tadi. Anda akan dapat mengetahui bagaimana menghitung jumlah dan selisih dari dua buah waktu yang berbeda.

Inilah jawaban selengkapnya!

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).";
}
 
?>

Jika Anda menjalankan kode di atas, maka akan menghasilkan sebagai berikut:

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 kali dibacaCetak Artikel Ini Cetak Artikel Ini

Komentar

  1. Arlia Widy mengatakan:

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

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

  2. Marijan Sivric mengatakan:

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

Utarakan pikiran Anda

*


*