在几分钟内得到 2 date_time 之间的差异

Get difference between 2 date_time in minutes

我试图以分钟为单位计算出 2 个不同日期之间的差异,但输出不正确。

例如:

$then = "2017-01-23 18:21:24";

//Convert it into a timestamp.
$then = strtotime($then);
//Get the current timestamp.
$now = time();

//Calculate the difference.
$difference = $now - $then;

//Convert seconds into minutes.
$minutes = floor($difference / 60);

echo $minutes;

正在输出 611 分钟,并且是错误的,因为从“2017-01-23 18:21:24”到“2017-01-24 12:36:24”已经超过了 611 分钟。我的代码不正确吗?

如果您正在使用或能够使用 PHP 5.3.x 或更高版本,您可以使用其 DateTime 对象功能:

$date_a = new DateTime('2010-10-20 08:10:00');
$date_b = new DateTime('2008-12-13 10:42:00');

$interval = date_diff($date_a,$date_b);

echo $interval->format('%h:%i:%s');

您可以通过多种方式使用该格式,一旦您在 DateTime 对象中有了日期,您就可以利用许多不同的功能,例如通过普通运算符进行比较。有关更多信息,请参阅手册:http://us3.php.net/manual/en/datetime.diff.php

尝试设置默认时区

date_default_timezone_set('Europe/Copenhagen');

Ofc 更改 Europe/Copenhagen 以满足您的需要。

我已经检查过你的代码,它运行良好 所以如果有任何疑问 see your result

但是你错了,所以要忽略这个设置你的时区。