使用 php 获取两个日期之间的总时差


Get total time difference between two dates using php

可能的重复项:
如何使用PHP计算两个日期之间的差异?

在这里,我提到了两次日期

2008-12-13 10:42:00

2010-10-20 08:10:00

我想以 (h:m:s( 格式获取总时差

如果您正在使用或能够使用 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

我使用什么:

$seconds = strtotime("2010-10-20 08:10:00") - strtotime("2008-12-13 10:42:00");
$days    = floor($seconds / 86400);
$hours   = floor(($seconds - ($days * 86400)) / 3600);
$minutes = floor(($seconds - ($days * 86400) - ($hours * 3600))/60);
$seconds = floor(($seconds - ($days * 86400) - ($hours * 3600) - ($minutes*60)));

您现在可以按照自己的方式格式化

您可以使用 strtotime 函数将时间转换为整数并减去它们。

$time1 = strtotime("2008-12-13 10:42:00");
$time2 = strtotime("2010-10-20 08:10:00");
$diff = $time2-$time1;
// the difference in int. then you can divide by 60,60,24 and 
// so on to get the h:m:s out of it