我编写了以下代码来确定员工在任务上花费的时间:
$time1 = $row_TicketRS['OpenTime'];
$time2= $row_TicketRS['CloseTime'];
$t1=strtotime($time1);
$t2=strtotime($time2);
$end=strtotime(143000); //143000 is reference to 14:30
//$Hours =floor((($t2 - $t1)/60)/60);
$Hours = floor((($end- $t1)/60)/60);
echo $Hours.' Hours ';
Run Code Online (Sandbox Code Playgroud)
上面的代码没有给我正确的时间.
例如,开始时间为09:19:00,结束时间为11:01:00,它给我的持续时间仅为1小时,这是错误的.什么是正确的方法?
您的使用floor就是为什么这些输入只需1小时.如果您将答案保持为浮点数,那么这些输入将导致1.7小时. floor自动向下舍入到较低的整数值.查看http://php.net/manual/en/function.floor.php了解更多信息.
$t1 = strtotime('09:19:00');
$t2 = strtotime('11:01:00');
$hours = ($t2 - $t1)/3600; //$hours = 1.7
Run Code Online (Sandbox Code Playgroud)
如果你想要更精细的时差,你可以把它充实......
echo floor($hours) . ':' . ( ($hours-floor($hours)) * 60 ); // Outputs "1:42"
Run Code Online (Sandbox Code Playgroud)
更新:
我刚刚注意到你对Long Ears回答的评论.请再次检查上面的评论,它们是正确的.输入'09:11:00'和'09:33:00'的值导致0小时(22分钟).
如果输入这些值并获得4小时,则数学中可能会出现小数误差.使用'09:11'到'09:33',结果是.367小时.如果您将strtotime结果除以360而不是3600,则结果为3.67小时(或4小时,具体取决于您的舍入方法).
strtotime 将您的时间转换为int表示自Unix纪元以来秒数的值.由于您将两个值都转换为秒,然后相互减去值,因此结果值是秒数.1小时内有3600秒.
改变strtotime('14:30:00') 一切后工作正常..见下文
$time1 = '09:19:00';
$time2= '11:01:00';
echo "Time1:".$t1=strtotime($time1);
echo "<br/>Time2:".$t2=strtotime($time2);
echo "<br/>End:".$end=strtotime('14:30:00');
echo "<br/>Floor value:";
var_dump(floor((($end- $t1)/60)/60));
//$Hours =floor((($t2 - $t1)/60)/60);
$Hours = floor((($end- $t1)/60)/60);
echo $Hours.' Hours ';
Run Code Online (Sandbox Code Playgroud)
小智 5
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;
}
echo getTimeDiff("23:30","01:30");
Run Code Online (Sandbox Code Playgroud)