为什么在尝试获取2个DateTime对象的diff()时会出现致命错误

时间:2016-01-10 01:50:22

标签: php datetime

我试图找出两个时间戳之间的天数差异(使用DateTime)。第一个是当前日期。第二个是存储在SQL DB中的预定日期

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

$dt = (new DateTime())->format('Y-m-d');

$username = $_SESSION['username'];
$sql = $conn->query("SELECT * FROM medications WHERE username = '$username'") or die(mysqli_error($conn));
if ($sql->num_rows > 0) {
    while($med = $sql->fetch_assoc()) {
        $medname = $med['medication'];
        $refill = $med['refilldate'];
        $refillby = (new DateTime($refill))->format('Y-m-d');
        $interval = $dt->diff($refillby); //Error Below Received on this Line
        echo $diff;
    }
}

以下是我收到的错误:

  

致命错误:在...

中的非对象上调用成员函数diff()

我在网上找到的所有内容都是Date和DateTime之间存在冲突,但我没有使用Date。另外,如果我echo我的$refillby变量,则其格式与$dt

的格式正确相同

1 个答案:

答案 0 :(得分:3)

正如评论所述,您无法格式化DateTime ...试试这个:

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

$dt = new DateTime();

$username = $_SESSION['username'];
$sql = $conn->query("SELECT * FROM medications WHERE username = '$username'") or die(mysqli_error($conn));
if ($sql->num_rows > 0) {
    while($med = $sql->fetch_assoc()) {
        $medname = $med['medication'];
        $refill = $med['refilldate'];
        $refillby = new DateTime($refill);
        $interval = $dt->diff($refillby);
        echo $interval->format('%R%a days'); //you need to make sure this var matches - it doesn't above.
    }
}