[英]finding out difference between two times
我编写了以下代码来确定员工在任务上花费的时间:
$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 ';
上面的代码没有给我正确的时间。
例如,开始时间为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
如果你想要更精细的时差,你可以把它充实......
echo floor($hours) . ':' . ( ($hours-floor($hours)) * 60 ); // Outputs "1:42"
更新:
我刚刚注意到你对Long Ears回答的评论。 请再次检查我的评论,它们是正确的。 输入'09:11:00'和'09:33:00'的值导致0小时(22分钟)。
如果输入这些值并获得4小时,则数学中可能会出现小数误差。 使用'09:11'到'09:33',结果是.367小时。 如果你将strtotime
结果除以360而不是3600,你会得到3.67小时(或4小时,取决于你的舍入方法)。
strtotime
将您的时间转换为表示自Unix纪元以来的秒数的int
值 。 由于您将两个值都转换为秒,然后相互减去值,因此结果值是秒数。 1小时内有3600秒。
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");
改变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 ';
更好的方法是使用http://php.net/manual/en/datetime.diff.php
$start_t = new DateTime($start_time);
$current_t = new DateTime($current_time);
$difference = $start_t ->diff($current_t );
$return_time = $difference ->format('%H:%I:%S');
你需要strtotime('14:30')
而不是strtotime(143000)
编辑:实际上令我惊讶的是, strtotime(143000)
似乎确实有预期的效果,但只有两位数的小时,所以我仍然不会依赖它。 无论如何,这不是你的问题的原因;)
例如,开始时间是09:19:00,结束时间是11:01:00但它给我的持续时间只有1小时,这是错误的
您正在计算小时数的差异。 “开始时间是09:19:00,结束时间是11:01:00”的正确结果是什么
你可以使用$hour = ($end - $t1)/(60*60)
在这个时间格式是(秒*分钟*天*月*年)=>(60 * 60 * 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.