时差 PHP

Time Difference PHP

我正在尝试构建一个技能跟踪器,显示用户学习某项特定技能的时间。结果,我有一个 while 循环遍历我数据库中的所有内容,但我一直在研究如何通过循环获取每次迭代的两次之间的差异。它们在 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);

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

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

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