我有两次$InTime
:12:55:10
而另一次是$OutTime
:12:56:10
所以我认为计算时差应该是:
$TotalTimeInOffice = $OutTime - $InTime
我想要几个小时,所以我认为这应该是结果00:01
,但我得到了错误的结果。通过这个计算,我在结果中得到0
,但为什么?
以下是数据库中的一些示例:
InTime is: 12:55:10
OutTime is: 12:56:09
Result Is: 0
InTime is: 12:24:45
OutTime is: 00:00:00
Result Is: -12
InTime is: 10:05:48
OutTime is: 10:06:11
Result Is: 0
和PHP代码将是。
$timestart = $time_sheets->in_time;
$timestop = $time_sheets->out_time;
$time_diff = $timestop - $timestart ;
echo "InTime is: $timestart <br />";
echo "OutTime is: $timestop <br />";
print_r('Result Is: '.$time_diff."<br />");
答案 0 :(得分:1)
您的代码在涉及午夜时失败,例如12:24:45 - 00:00:00
返回-12:24:45
。如果它们位于午夜的任何一侧,则需要更正时间:
function getDuration($timestart, $timestop) {
$time1 = new DateTime("today " . $timestart);
$time2 = new DateTime("today " . $timestop);
if ($time2 < $time1) {
$time2 = new DateTime("tomorrow " . $timestop);
}
$time_diff = $time1->diff($time2);
echo " InTime is: $timestart\n";
echo "OutTime is: $timestop\n";
echo " Result is: " . $time_diff->format("%r%H:%I:%S") . "\n\n";
}
getDuration("12:55:10", "12:56:09");
getDuration("12:24:45", "00:00:00");
getDuration("10:05:48", "10:06:11");
getDuration("11:00:00", "01:00:00");
输出:
InTime is: 12:55:10
OutTime is: 12:56:09
Result is: 00:00:59
InTime is: 12:24:45
OutTime is: 00:00:00
Result is: 11:35:15
InTime is: 10:05:48
OutTime is: 10:06:11
Result is: 00:00:23
InTime is: 11:00:00
OutTime is: 01:00:00
Result is: 14:00:00
答案 1 :(得分:0)
我猜你应该使用strtotime()将它转换为time(); 然后使用$ timeOutTime - $ timeInTime;
$timestart = $time_sheets->in_time;
$timestop = $time_sheets->out_time;
$timestart = strtotime($timestart);
$timestop = strtotime($timestop);
$time_diff = $timestop - $timestart ;
echo data("h:i:s",$time_diff);
这应该有效。
答案 2 :(得分:0)
// Change It
$time1 = new DateTime($timestart);
$time2 = new DateTime($timestop);
// $time_diff = $timestop - $timestart ;
$time_diff = $time1->diff($time2);
echo "InTime is: $timestart <br />";
echo "OutTime is: $timestop <br />";
print_r('Result Is: ' . $time_diff->format('%H:%I:%s') . "<br />");
// End of Change
使用DateTime函数解决问题,但如果还有其他好/更好的方法,那么请发布该答案..