在php中计算不同的时间

时间:2012-12-01 04:02:55

标签: php time date-arithmetic

我想计算数据库中不同btw当前时间和时间的时间。数据库中的时间格式是日期时间("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(); }

?>

2 个答案:

答案 0 :(得分:3)

如何计算查询?

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

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

答案 1 :(得分:1)

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>