![](/img/trans.png)
[英]Date_diff() expects parameter 2 to be DateTimeInterface, Boolean Given
[英]I need to subtract a mySQL timestamp with a PHP timestamp. Getting a “date_diff() expects parameter 1 to be DateTimeInterface, array given” error
我覺得這應該很容易,但是我被困了很長時間,以至於我正在向我的 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
知道我做錯了什么嗎?
以下是我在上述用戶的建議下最終解決的方法。
$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() function 的關鍵。
date_diff()
不接受 2 個日期作為字符串
所以你必須先將字符串轉換為 DateTime object
// 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.