Reputation: 105
i try to get time difference between two time schedules in php but its not working properly.
$stime="10:00 pm";
$sptime="11:30 pm";
//convert into 24hr format
$Cstime = date("H:i:s", strtotime($stime));
$Csptime = date("H:i:s", strtotime($sptime));
//call the method
$diff=get_time_different($Cstime,$Csptime);
//define method
function get_time_different($Cstime,$Csptime)
{
$Cstime = strtotime("1/1/1980 $Cstime");
$Csptime = strtotime("1/1/1980 $Csptime");
if($Csptime<$Cstime)
{
$Csptime = $Csptime+ 86400;
}
return($Csptime-$Cstime) / 3600;
}
echo $diff;
OUTPUT
1.5
but i need 1.30. what is the problem
Upvotes: 1
Views: 53
Reputation: 1305
Try this:
$stime="10:00 pm";
$sptime="11:30 pm";
$time1 = new DateTime(date('H:i:s',strtotime($stime)));
$time2 = new DateTime(date('H:i:s',strtotime($sptime)));
$diff = $time1->diff($time2);
echo $diff->h.'.'.$diff->i;
Output:
1.30
Now, as you can see the variable '$diff' is a object and you have acccess to hours,minutes, seconds..
public 'y' => int 0
public 'm' => int 0
public 'd' => int 0
public 'h' => int 1
public 'i' => int 30
public 's' => int 0
public 'weekday' => int 0
public 'weekday_behavior' => int 0
public 'first_last_day_of' => int 0
public 'invert' => int 0
public 'days' => int 0
public 'special_type' => int 0
public 'special_amount' => int 0
public 'have_weekday_relative' => int 0
public 'have_special_relative' => int 0
Upvotes: 1
Reputation: 7149
Try this code to convert hours to time format,
//$diff = 1.5;
$min = $diff*60;
$time = gmdate("H:i", ($min * 60));
echo $time; // output : 01:30
Upvotes: 0