2

我尝试比较 2 个日期时间并以分钟和秒为单位得到不同,在我参考这个主题后如何在 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.

4

2 回答 2

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

echo "$minutes minute, $seconds seconds";
于 2013-05-08T02:23:58.570 回答
2

或者使用PHP >= 5.3的DateTime 类:-

$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');
于 2013-05-09T11:59:27.293 回答