计算分钟和秒的不同时间

时间:2013-05-08 02:18:18

标签: php datetime

我尝试比较2个日期时间,并在分钟和秒后得到不同,在我推荐这个主题之后How to get time difference in minutes in PHP是的,代码可以显示不同但是在分钟内:

$to_time = strtotime("2008-12-13 18:42:00");
$from_time = strtotime("2008-12-13 18:41:58");

echo round(abs($to_time - $from_time) / 60,2). " minute";

那么如何从上面的代码中显示分钟和秒?我的php版本是5.2.17

2 个答案:

答案 0 :(得分:3)

$minutes = round(abs($to_time - $from_time) / 60,2);
$seconds = abs($to_time - $from_time) % 60;

echo "$minutes minute, $seconds seconds";

答案 1 :(得分:2)

或者使用DateTime class for PHP> = 5.3: -

$to_time = new \DateTime('2008-12-13 18:42:00');
$from_time = new \DateTime('2008-12-13 18:41:58');
$diff = $from_time->diff($to_time);
echo $diff->format('%i Minutes %s Seconds');

注意:`$ diff'将是DateInterval的实例。

或者,更简洁,但不太可读: -

$to_time = new \DateTime('2008-12-13 18:42:00');
$from_time = new \DateTime('2008-12-13 18:41:58');

echo $to_time->diff($from_time)->format('%i Minutes %s Seconds');