我已经四处寻找并测试了不同的解决方案,但似乎我没有让它发挥作用。
在MySQL中,我有一个列出工作日时间的表: ID,sheet_id,工作时间,电话,会议,咖啡,教育,清洁(除了ID,sheet_id,所有字段都是TIME)
首先,它不按我的意愿计算。 (我已经更改了下面的代码,以便更容易看到。)
$sql = "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(`workhours`))) AS totalworkhours
, SEC_TO_TIME(SUM(TIME_TO_SEC(`phonecall`))) AS totalphonecall
, SEC_TO_TIME(SUM(TIME_TO_SEC(`meeting`))) AS totalmeeting
, SEC_TO_TIME(SUM(TIME_TO_SEC(`coffe`))) AS totalcoffe
, SEC_TO_TIME(SUM(TIME_TO_SEC(`education`))) AS totaleducation
, SEC_TO_TIME(SUM(TIME_TO_SEC(`clean`))) AS totalclean FROM working WHERE sheet_id = '$working_id'";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$per_workhours = $row['totalworkhours'];
echo "Total workhours: ". $per_workhours."<br />";
$per_phonecall = $row['totalphonecall'];
echo "Total phonecalls: ". $per_phonecall."<br />";
等等一切似乎都很好......
Total workhours: 33:00:00
Total phonecalls: 16:53:00
Total coffe: 02:02:00
Total clean: 02:02:00
Total other: 02:02:00
Total other: 02:02:00
Total other: 02:02:00
Total other: 02:02:00
但这让我头疼不已:
Calc1表示总共12(12:18),但它应该是12:12
$no_time = $per_coffe + $per_clean + $other1 + $other2 + $other3 + $other4;
echo "Calc 1: ". $no_time ." (".date('H:i', mktime($no_time)).")<br />";
$per_time = $per_workhousrs - $no_time;
$percent = round(($per_time/$per_workhours)*100);
我确实简化了很多重复的代码。但我想总结一下。减去非需要时间并以百分比计算实际工作时间。
答案 0 :(得分:2)
正如Flying所说,如果你要添加字符串值,php将提取初始数字(在本例中是小时部分)并添加它们,丢弃其他所有内容。
您可以使用这些函数将时间字符串转换为秒数并再返回(类似于MySQL的SEC_TO_TIME
和function timeToSeconds($time)
{
$sign = 1;
if (strncmp($time, '-', 1) === 0) {
$time = substr($time, 1);
$sign = -1;
}
list($hours, $minutes, $seconds) = explode(':', $time, 3) + array(0, 0, 0);
return $sign * (($hours * 3600) + ($minutes * 60) + $seconds);
}
function secondsToTime($seconds)
{
$sign = '';
if ($seconds < 0) {
$sign = '-';
$seconds = -$seconds;
}
$hours = floor($seconds / 3600);
$seconds %= 3600;
$minutes = floor($seconds / 60);
$seconds %= 60;
return sprintf('%s%02d:%02d:%02d', $sign, $hours, $minutes, $seconds);
}
函数):
$no_time = timeToSeconds($per_coffe) + timeToSeconds($per_clean) + timeToSeconds($other1) + timeToSeconds($other2) + timeToSeconds($other3) + timeToSeconds($other4);
echo "Calc 1: ". $no_time ." (". secondsToTime($no_time) . ")<br />";
$per_time = timeToSeconds($per_workhours) - $no_time;
$percent = round(($per_time/timeToSeconds($per_workhours))*100);
echo $percent . "%<br />";
然后您的代码可以修改为:
Calc 1: 43920 (12:12:00)
63%
其中(使用示例中的值)应该给出:
secondsToTime()
修改SQL查询可能更容易以秒为单位返回值,然后可以直接在PHP中添加,并使用{{1}}函数格式化显示。