PHP - 以秒为单位获取两个日期时间之间的差异

时间:2015-10-09 14:31:19

标签: php date datetime strtotime

我有一个日期时间值,我想要现在的日期时间和日期时间之间的差异..我试图将其转换为时间戳并计算差异,但我得到一个负值。如何在几秒钟内获得差异?

<?php 
$datetimenow = strtotime(date("Y/m/d H:i:s"));
$mydatetime = strtotime(date('2015/10/09 14:20:00'));
echo ($datetimenow - $mydatetime);
?>

2 个答案:

答案 0 :(得分:9)

使用DateTime class代替,即:

date_default_timezone_set('Europe/Lisbon'); //set your desired timezone
$now = new DateTime( 'NOW' );
$future = new DateTime( '2015/10/09 15:20:00' );
$diffSeconds = $now->getTimestamp() - $future->getTimestamp();
# 2220

答案 1 :(得分:1)

我喜欢Carbon库...... https://github.com/briannesbitt/Carbon

$diff = Carbon::now()->diffInSeconds(Carbon::parse('2015/10/09 14:20:00'));
相关问题