Php减去两个日期

时间:2016-01-08 22:46:46

标签: php datetime subtraction

我从mysql数据库获取$ status_date,当我回显$ status_date时,它看起来像这样 - > 2016-01-08 22:18:14我现在设置$,当我回显它看起来像这样 - > 2016-01-08 22:43:27我想从$ now中减去$ status_date。这是我的代码:

$now = date("Y-m-d H:i:s");  
$status_date = date("Y-m-d H:i:s",strtotime($row['status_date']));
$x = $now-$status_date;

$ x返回此 - > 0

为什么不减法?

3 个答案:

答案 0 :(得分:1)

日期不会这样减去。将两个日期转换为时间,减去并转换回日期。

$now = strtotime(date("Y-m-d H:i:s"));
$status_date = strtotime($row['status_date']);
$x = date($now-$status_date);

但是如果你想在日期之间花时间考虑时刻库。

https://github.com/fightbulc/moment.php

答案 1 :(得分:0)

根据release notes

检查我在这里写的代码: http://php.net/manual/en/datetime.diff.php

<?php 

$strStart = '2015-01-08 22:18:14'; // status  date
$strEnd = 'now';  

$dteStart = new DateTime($strStart); 
$dteEnd   = new DateTime($strEnd); 

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

print $dteDiff->format("%Y-%m-%d %H:%I:%S"); 

thre result is smth like : 01-0-0 00:38:42

答案 2 :(得分:0)

您还可以使用以下内容:

$now = new DateTime();
$status_date = new DateTime($row['status_date']);
$diff = $now->diff($status_date);

然后你可以使用任何dateInterval属性或函数与$ diff。

文档:http://php.net/manual/es/datetime.diff.php http://php.net/manual/es/class.dateinterval.php

相关问题