Mengambil nilai jarak antara dua tanggal dan jam

This item was filled under [ Code Snippet, PHP ]

Fungsinya adalah sbb:

// DATE DIFF
function jin_date_diff($d1, $d2){
    $d1 = (is_string($d1) ? strtotime($d1) : $d1);
    $d2 = (is_string($d2) ? strtotime($d2) : $d2);
 
    $diff_secs = abs($d1 - $d2);
    $base_year = min(date("Y", $d1), date("Y", $d2));
 
    $diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
    return array(
        "years" => date("Y", $diff) - $base_year,
        "months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
        "months" => date("n", $diff) - 1,
        "days_total" => floor($diff_secs / (3600 * 24)),
        "days" => date("j", $diff) - 1,
        "hours_total" => floor($diff_secs / 3600),
        "hours" => date("G", $diff),
        "minutes_total" => floor($diff_secs / 60),
        "minutes" => (int) date("i", $diff),
        "seconds_total" => $diff_secs,
        "seconds" => (int) date("s", $diff)
    );
}

penggunaan:

$a = "2008-01-01 09:30:23";
$b = "2008-01-02 12:45:10";
$hasil = jin_date_diff($a, $b);
print_r($hasil);
// $hasil['years'] <-- jumlah tahun
// $hasil['days_total'] <-- jumlah total bulan
// $hasil['months'] <-- jumlah bulan
// $hasil['days'] <-- jumlah total hari
// dlsb.... (lihat pada fungsi)

maka akan keluar hasil array… lalu kita ambil yg kita perlukan dari array tersebut..

Update: saya ubah nama fungsinya menjadi jin_date_diff, karena date_diff sudah dipakai pada PHP 5.3.0 keatas akan tetapi berbeda hasil fungsi nya, silahkan lihat manualnya di http://id2.php.net/manual/en/function.date-diff.php

Rate this topic:
1 Star2 Stars3 Stars4 Stars5 Stars (8 votes, average: 5.00 out of 5)
Loading ... Loading ...
Popularity: 2,022 views
Tagged with: [ , , , ]
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Artikel Sejenis

Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.

Halaman ini di eksekusi dalam waktu 1.348 detik! (koneksi mayan bagus nih...)