Pages

Selasa, 02 April 2013

Selisih tanggal dengan php

Fungsi untuk melakukan pengurangan tanggal pada PHP.
<?php
public function cekSelisihHari($start, $end) {
        $hari1 = explode(" ", $start); //memisahkan date dengan time
        $tgl1 = $hari1[0];
        $tgl1 = explode("-", $tgl1);//memisahkan tahun, bulan dan tanggal
        $hari2 = explode(" ", $end);
        $tgl2 = $hari2[0];
        $tgl2 = explode("-", $tgl2);
        if (((int)$tgl2[0] - (int)$tgl1[0]) == 0) {
            if (((int)$tgl2[1] - (int)$tgl1[1]) == 0) {
                if (((int)$tgl2[2] - (int)$tgl1[2]) == 0) {
                    return 0;
                } else {
                   return (int)$tgl2[2] - (int)$tgl1[2];
                }
            } else { 
                if(((int)$tgl2[1]-(int)$tgl1[1])>0){
                    $num = cal_days_in_month(CAL_GREGORIAN, $tgl1[1], $tgl1[0]);
                    for($i=1; $i<((int)$tgl2[1]-(int)$tgl1[1]);$i++){                      
                        $num += cal_days_in_month(CAL_GREGORIAN, (int)$tgl1[1]+1, $tgl1[0]);                   
                    }
                }                
                $temp = $num - (int)$tgl1[2];
                return $temp + (int)$tgl2[2];
            }
        } else {
            $num = cal_days_in_month(CAL_GREGORIAN, $tgl1[1], $tgl1[0]);
            echo $num;
            $temp = $num - (int)$tgl1[2];
            return $temp + (int)$tgl2[2];
        }
        return 0;
    }

?>
contoh penggunaan :
$a = "2013-02-25"; //bisa dengan format datetime seperti '2013-02-25 03:03:55'
$b = "2013-04-02";
echo cekSelisihHari($a,$b);