时差PHP

时间:2015-07-02 13:43:58

标签: php time difference

我正在尝试构建一个技能跟踪器,显示用户学习特定技能的时间。结果,我有一个循环遍历我的数据库中的所有内容,但我仍然坚持如何通过循环每次迭代两次之间的差异。它们在12小时的时间内被格式化为H:m:s(例如09:05:00)。

例如,假设我在2015年7月2日的日期工作了两项技能。结果应如下所示:

| Skill Name | Time Started | Time Finished | Difference |
| ---------- | ------------ | ------------- | ---------- |
| Bootstrap  | 9:05:00 AM   | 11:15:00 AM   |  2:10:00   |
| CSS        | 10:50:00 PM  | 11:50:00 PM   |  1:00:00   |
| Python     | 10:00:00 AM  | 1:00:00 PM    |  3:00:00   |

这是我的代码(请原谅已弃用的陈述。这只会由我使用):

     $skilltoview = $_POST['skilltoview'];

        include("db.php");

        //retrieve data from database
        $result = mysql_query("SELECT * FROM timer WHERE skillname='$skilltoview'");


        echo "<div class='table-responsive'>";
        echo "<table class='table table-striped table-bordered'>";
        echo "<thead>";
        echo "<tr>";
        echo "<th>ID</th><th>Skill Name</th><th>Skill Date</th><th>Time Started</th><th>Time Ended</th><th>Notes</th><th>Difference</th>";
        echo "</tr></thead>";
        echo "<tbody>"; 

        function timeDifference($timeEnd, $timeStart){
        $tResult = strtotime($timeEnd) - strtotime($timeStart);
        return date("G:i", $tResult);
        }


    while($row = mysql_fetch_array($result)){
        $id = $row['id'];
        $start = $row['timestarted'];
        $stop = $row['timestopped'];

        echo "
        <tr>
            <td>$id</td>
            <td>$row[skillname]</td>
            <td>$row[date]</td>
            <td>$row[timestarted]</td>
            <td>$row[timestopped]</td>
            <td>$row[notes]</td>
            <td>"; print(timeDifference($start, $stop)); echo "</td>
            <td><a href ='edittracker.php?id=$id'>Edit</a>
            <td><a onClick='deleteConfirm(); return false;' href='#'><center>Delete</center></a></a>
        </tr>";

        echo "<script type='text/javascript'>
        function deleteConfirm(){
        var r = confirm('Are you sure you want to delete this skill log?');
        if (r == true) {
        window.location='deletetracker.php?id=$id';
        } else {
            x = 'You pressed Cancel!';
        }
        }
        </script>";
    }
        echo "</tbody>"; 
        echo "</table>";
        echo "</div>"; 

        //close connection
        mysql_close($conn);

1 个答案:

答案 0 :(得分:1)

无论php代码有什么问题,您都可以让数据库服务器轻松计算差异;使用TIMEDIFF并将其添加到您的查询中:

SELECT *, TIMEDIFF(timestopped, timestarted) as diff FROM timer WHERE skillname='$skilltoview'

然后您可以直接打印<td>$row[diff]</td>