Reputation: 3207
I wanna get the difference between specific number of hours, as I'm working on payroll project which requires to get total working hours of an employee.
let's say the employee has worked for 40:18:20 (hh:mm:ss) And he missed to work for 12:15:10 (hh:mm:ss)
I want to get the difference between those two times as following: (40:18:20) - (12:15:10) = (28:03:10)
Is it possible via PHP functions?
What I actually did, is to split that as string, and tried to subtract each number individually and then recollect them again, which is "as I think" is not professional.
Please advise.
Upvotes: 0
Views: 140
Reputation: 866
Another solution with mktime:
$diff return a timestamp then you need to convert it in hh:mm:ss
$diff = mktime(40,18,20)-mktime(12,15,10);
$hours = $diff/3600 %3600;
$minutes = $diff/60 %60;
$seconds = $diff % 60;
$time= $hours.":".$minutes.":".$seconds;
Upvotes: 0
Reputation: 974
this will handle hours greater then 24.
$start = date_create(gmdate('D, d M Y H:i:s',timeTosec('40:18:20')));
$end = date_create(gmdate('D, d M Y H:i:s',timeTosec('12:15:10')));
$diff=date_diff($end,$start);
print_r($diff);
function timeTosec($time){
sscanf($time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
return $time_seconds;
}
Upvotes: 0
Reputation: 1
This will handle differences greater than 24 hours. Code is maybe a bit too broken down, but on the other hand it is easy to understand.
// Use any valid date in both cases
$a = new DateTime(date("Y-m-d H:i:s", mktime(5, 20, 15, 12, 31, 2016)));
$b = new DateTime(date("Y-m-d H:i:s", mktime(65, 10, 5, 12, 31, 2016)));
$c = $a->diff($b);
$days = $c->format("%a");
$hours = intVal($c->format("%H")) + intVal($days);
$minutes = $c->format("%m");
$seconds = $c->format("%s");
// Unformatted result
print $hours . ':' . $minutes . ':' . $seconds;
Upvotes: 0
Reputation: 39
you can use this function
function getTimeDiff($dtime,$atime){
$nextDay=$dtime>$atime?1:0;
$dep=explode(':',$dtime);
$arr=explode(':',$atime);
$diff=abs(mktime($dep[0],$dep[1],0,date('n'),date('j'),date('y'))-mktime($arr[0],$arr[1],0,date('n'),date('j')+$nextDay,date('y')));
//Hour
$hours=floor($diff/(60*60));
//Minute
$mins=floor(($diff-($hours*60*60))/(60));
//Second
$secs=floor(($diff-(($hours*60*60)+($mins*60))));
if(strlen($hours)<2)
{
$hours="0".$hours;
}
if(strlen($mins)<2)
{
$mins="0".$mins;
}
if(strlen($secs)<2)
{
$secs="0".$secs;
}
return $hours.':'.$mins.':'.$secs;
}
Upvotes: 1