减去日期变量PHP

时间:2013-11-22 06:44:40

标签: php

Helllo,我有2个时间变量。我从数据库中获取一个,另一个是当前时间。

$time_ended = $row['time_ended'];
$time_ended = new DateTime($time_ended);
$now = new DateTime();

我想要的是从$ time_ended中减去$ now并回显结果中的秒数。 基本上输出应该是121或134.我需要这些数据来创建一个倒数计时器。 有人能告诉我这招吗? 谢谢你的时间。

2 个答案:

答案 0 :(得分:1)

  

PHP> 5.3:http://php.net/datetime.diff

     

PHP< 5.3:http://php.net/strtotime

使用diff方法:

// PHP > 5.3
$diff = $time_ended->diff( $now );
echo $diff->format( '%s' ); // Seconds, with leading zeros

或者,如果您没有运行PHP> 5.3:

// PHP < 5.3
$diff = ( strtotime( $now ) - strtotime( $time_ended ) ) / 3600;
echo date( 's', $diff ); // Seconds, with leading zeros

答案 1 :(得分:1)

http://php.net/manual/en/datetime.diff.php

使用DateTime对象的diff方法。

$interval = $time_ended->diff($now);
$diff_seconds = $interval->s; // returns the number of seconds

这将返回DateInterval(http://www.php.net/manual/en/class.dateinterval.php)对象。 s属性获取间隔的秒数。

相关问题