【问题标题】:I need to subtract a mySQL timestamp with a PHP timestamp. Getting a "date_diff() expects parameter 1 to be DateTimeInterface, array given" error我需要用 PHP 时间戳减去 mySQL 时间戳。获取“date_diff() 期望参数 1 是 DateTimeInterface,给定数组”错误
【发布时间】:2020-10-12 13:33:19
【问题描述】:

我觉得这应该很容易,但我被困了很长时间,所以我正在向我的 stackoverflow 朋友寻求帮助。我要做的就是从我的 mySQL 表中获取当前时间戳,然后从当前 php 服务器时间戳中减去它。 mySQL 格式是

chat_time 时间戳 current_timestamp()

插入完成后的样子

2020-06-22 14:51:41

所以在我的 php 代码中我写了这个

//chat countdown logic
$curDate = getdate();
$mysqlTimestamp = $row['chat_time'];

$dif=date_diff($curDate,$mysqlTimestamp);

$row['chat_time'] = $dif;
//end of chat countdown logic

知道我做错了什么吗?

【问题讨论】:

  • 当你开始var_dump()'ing / echoing 时你会得到什么?与预期结果相反,您得到了什么结果?数据库中有哪些值?
  • getdate() 正在返回一个数组,而不是 DateTime 对象。
  • 您查看手册了吗? php.net/manual/en/datetime.diff.php
  • @FunkFortyNiner 谢谢,我想我忽略了新的 DateTime() ......我有它在使用 $dteStart = new DateTime($row['chat_time']);
  • 欢迎@CJBroersma 很高兴看到您提出解决方案。

标签: php mysql date


【解决方案1】:

在上述用户的建议下,我最终解决了这个问题。

$dteStart = new DateTime($row['chat_time']);
$dteEnd   = new DateTime("now");

$dteDiff  = $dteStart->diff($dteEnd);

$row['chat_time'] = $dteDiff->format("%H:%I:%S");

创建新的 DateTime() 是同步数据库和 php 日期以便使用 diff() 函数的关键。

【讨论】:

    【解决方案2】:

    date_diff() 不接受 2 个日期作为字符串

    the manual

    所以你必须先将字符串转换为 DateTime 对象

    // date time now
    $curDate = new DateTime();      
    
    // make a datetime object from a timestamp
    $mysqlTimestamp = (new DateTime)->setTimestamp($row['chat_time']);
    
    $diff = date_diff($curDate, $mysqlTimestamp);
    $print_r($diff);    // see what you get
    

    【讨论】:

    • 非常感谢您的回复。我在 $mysqlTimestamp = (new DateTime)->setTimestamp($row['chat_time']); 上收到“遇到格式不正确的数值”错误
    • 你能显示$row['chat_time'] 中的实际内容吗?请执行var_dump($row['chat_time']); 并发布结果
    猜你喜欢
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多