2013-05-11 107 views
0

我已阅读过几篇文章,但对于它的工作方式我还是有点困惑。与php的日期时间差异

我想比较2次。第一次是NOW的时间,第二次是来自数据库的日期时间。我能够在几天,几个月和几年中获得差异,但是当我尝试获取分钟和秒钟时,数字看起来不正确。

这里是我得到以分和秒的时间代码:

$date1 = date('Y-m-d H:i:s'); 
$date2 = $blah['datetime']; //the variable here is in dateTime format coming from the database 
$diff = abs(strtotime($date2) - strtotime($date1)); //Does this give the seconds? 
$mins = floor($diff/60); 

到目前为止分钟它返回像560,即使我添加了一行(对数据库中的表)一分钟前。也许我误解了一些东西,或者错过了一些东西。让我知道你是否希望我澄清任何事情。谢谢!

+0

向我们展示'$ date1'和'$ date2'的值。 – deceze 2013-05-11 19:50:19

+0

$ date1和$ date2都具有相同的格式日期('Y-m-d H:i:s')。 $ date1是现在的日期(当前时间),$ date2是过去存储的日期格式。你需要知道确切的日期和时间吗? – tickerll 2013-05-11 19:54:01

+0

尽管如此,日期如下:$ date1 = 2013-05-11 21:55:19 $ date2 = 2013-05-11 12:49:12 – tickerll 2013-05-11 19:55:50

回答

0

这个计算对于PHP的DateTimeDateInterval类很容易。

$date1 = new \DateTime(); 
$date2 = \DateTime::createFromFormat('Y-m-d H:i:s', $blah['datetime']); 
$diff = $date1->diff($date2); // $diff is an Instance of DateInterval 

$mins = ($diff->days * 60 * 24) + ($diff->h * 60) + $diff->i;