Friday 26 August 2011

how to calculate time between two days in php


<?php function time_diff($start_dt,$end_dt)
{
//Seperate all values of the start date.
$st_arr = explode(' ',$start_dt);
$st_arr1 = explode('-',$st_arr[0]);
$st_arr2 = explode(':',$st_arr[1]);

$st_year = $st_arr1[0];
$st_month = $st_arr1[1];
$st_day = $st_arr1[2];
$st_hour = $st_arr2[0];
$st_min = $st_arr2[1];
$st_sec = $st_arr2[2];

//Seperate all values of the end date.
$end_arr = explode(' ',$end_dt);
$end_arr1 = explode('-',$end_arr[0]);
$end_arr2 = explode(':',$end_arr[1]);

$end_year = $end_arr1[0];
$end_month = $end_arr1[1];
$end_day = $end_arr1[2];
$end_hour = $end_arr2[0];
$end_min = $end_arr2[1];
$end_sec = $end_arr2[2];

$epoch_1= @mktime($end_hour,$end_min,$end_sec,$end_month,$end_day,$end_year);
$epoch_2 = @mktime($st_hour,$st_min,$st_sec,$st_month,$st_day,$st_year);

echo $epoch_1."<br/>";
echo $epoch_2."<br/>";

$diff_seconds  = $epoch_1 - $epoch_2;
//echo diff_seconds%3600;
    $diff_weeks    = floor($diff_seconds/604800);
$diff_seconds -= $diff_weeks * 604800;
$diff_days     = floor($diff_seconds/86400);
// echo "Dayes :".$diff_days."<br/>";
$diff_seconds -= $diff_days * 86400;
$diff_hours    = floor($diff_seconds/3600);
// echo "Dayes :".$diff_hours."<br/>";
$diff_seconds -= $diff_hours * 3600;
$diff_minutes  = floor($diff_seconds/60);
$diff_seconds -= $diff_minutes * 60;


if(($diff_hours>0) && ($diff_minutes>0) && ($diff_seconds>0)  && ($diff_days>0))
{
   $diff_days=$diff_days*24;
   $diff_hours=$diff_hours+ $diff_days;
$all = $diff_hours.'.'.$diff_minutes.' hrs';
return $all;
}

if(($diff_hours>0) && ($diff_minutes>0) && ($diff_seconds>0))
{
$all = $diff_hours.'.'.$diff_minutes.' hrs';
return $all;
}
else if($diff_minutes>0)
{
return $diff_minutes.' Min';
}
else if($diff_seconds>0)
{
return $diff_seconds.' Sec';
}
}

echo  time_diff( '2011-08-02 15:44:30','2011-08-04 06:04:29');

?>