我收到了以下代码:
$now = new DateTime();
$then = new DateTime($accountExists['sub_limit']);
$interval = $then->diff($now);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
返回2个日期时间(以分钟为单位)之间的差异。如果then
为2015-05-31 19:15:31
且now
为2015-05-31 19:20:31
,则返回5分钟。但是,只要一天发生变化,如果then
更改为2015-05-30 19:15:31
,它仍然会返回5分钟,此时应该是1445分钟。有人可以指出我的错误吗?
答案 0 :(得分:4)
因为几个月,几年可以有任意数分钟,你最好将日期转换为时间戳(自纪元以来的秒数),所以你只需要除以60.幸运的是,这很容易做到:
$now = new DateTime('2015-05-31 19:20:31');
$then = new DateTime('2015-05-30 19:15:31');
$seconds = abs($now->format('U') - $then->format('U'));
$minutes = floor($seconds / 60);
print $minutes;
答案 1 :(得分:0)
那是因为它整整一天。所以你必须计算一天的分钟数。所以这对你有用:
基本上,我只是从区间中获取所有days
,hours
,minutes
和seconds
,并将它们乘以乘数以获得分钟数。
<?php
//Test data
$now = "2015-05-30 19:20:31";
$accountExists['sub_limit'] = "2015-05-30 19:15:31";
$now = new DateTime($now);
$then = new DateTime($accountExists['sub_limit']);
$interval = $then->diff($now);
$multiplier = ["days" => 60*24, "h" => 60, "i" => 1, "s" => 1/60];
$minutes = 0;
$values = array_intersect_key((array)$interval, $multiplier);
foreach($values as $k => $v)
$minutes += $v*$multiplier[$k];
echo "Diff. in minutes is: " . $minutes;
?>
输出:
Diff. in minutes is: 1445