尝试使用(当前 php 日期 - mySQL 时间戳 = 天差)进行计算


Trying to calculate using (current php date - mySQL timestamp = difference in days)

我已经浏览了网站上的问题,我认为我遇到的问题更深入一些。我尝试使用 difftime() 函数,但它对我来说是 0。

到目前为止,这就是我所做的

$currentDate =  time();
//echo $printDate;
//echo $currentDate;
$editedDate = date("Y-m-d ", strtotime($printDate)); 
$editedCurrentTime = date("Y-m-d ", $currentDate); 

echo "$editedDate </br>";
echo "$editedCurrentTime </br>";
$timeDiff = ($editedCurrentTime - $editedDate);
echo "$timeDiff </br>";
$numberDays = floor($timeDiff/(60*60*24));

我首先将 time(); 保存到当前日期中,printDate 具有条目放入数据库的日期。两者都已格式化,并且回显会像应有的那样正确打印出来。第三个回声是减法由于某种原因变为 0 的地方。当我尝试使用strtotime($currentDate)时,editedCurrentTime的回声变成了1970-01-01。我猜这是一个小问题,与它们采用不同格式的事实有关,但它仍然让我感到困惑。任何帮助将不胜感激。

下面是输出的一个片段:

2012-08-01 
2012-08-08 
0 
2012-08-01 
2012-08-08 
0 
2012-08-01 
2012-08-08 
0 
2012-08-02 
2012-08-08 
0 

date() 函数根据您输入的格式返回一个字符串。不能对字符串执行算术运算。

您应该做的是首先计算从数据库中检索的时间戳(整数)的差异并time()然后才使用 date() 函数格式化此差异。

(注意:您也应该在数据库中以Unix纪元整数格式存储日期和时间。

你在找这个吗?如何使用 PHP 计算两个日期之间的差