1

我想计算数据库中当前时间和时间的不同时间。数据库中的时间格式是日期时间("Y-m-d H:i:s")。这是我的代码。我是 php 新手,如果我写了一个愚蠢的代码,我深表歉意。

<?php
try { 
    $dbh = new PDO("mysql:host=$hostname;dbname=", $username, $password);


    $sql = "select * from time";
    echo "<table>";
    echo "<tr><th>ID</th><th>Name</th><th>Time</th></tr>";
    foreach ($dbh->query($sql) as $row)
        {
        $id=$row['id'];
        echo "<tr>";
        echo "<td>" . $row['id'] ."</td>";
        echo "<td>" . $row['name'] . "</td>";
        echo "<td>" . $row['time'] . "</td>";

        echo "</tr>";
        }
    echo "</table>";
    $today=date("Y-m-d H:i:s");
    $timeleft=($row['time']-$today);
    echo $today;
    echo 'Time left: '.$timeleft;
        $dbh = null;
    }
    catch(PDOException $e) { echo $e->getMessage(); }

?>
4

2 回答 2

3

如何计算查询?

$sql = "select *, (t.time - NOW()) AS 'difference' from time t";

然后你只需要 echo echo'Time left: ' . $row['difference'];

于 2012-12-01T04:11:37.863 回答
1
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?> 
于 2012-12-01T04:08:23.407 回答