Helllo,我有2个时间变量。我从数据库中获取一个,另一个是当前时间。
$time_ended = $row['time_ended'];
$time_ended = new DateTime($time_ended);
$now = new DateTime();
我想要的是从$ time_ended中减去$ now并回显结果中的秒数。 基本上输出应该是121或134.我需要这些数据来创建一个倒数计时器。 有人能告诉我这招吗? 谢谢你的时间。
答案 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
属性获取间隔的秒数。