4

I have a datetime value I want the difference between that datetime and datetime now .. I tried to convert it to timestamp and calculate the difference but I got a negative value. How to get the difference in seconds ?

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

2 Answers2

13

Use the DateTime class instead, i.e.:

date_default_timezone_set( 'Europe/Lisbon' ); //set your desired timezone
$now = new DateTime( 'NOW' );
$future = new DateTime( '2015/10/09 15:20:00' );
$diffSeconds = $future->getTimestamp() - $now->getTimestamp();
# 2220
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • ... or `Datetime::diff()->format()` : http://php.net/manual/en/datetime.diff.php ... but you get an upvote anyway for using `DateTime` ;) – CD001 Oct 09 '15 at 14:49
  • 2
    @CD001 that option doesn't provide more than 59 seconds. But I had the same thought initially. – John Conde Oct 09 '15 at 14:57
  • @PedroLobito Thank you for your answer, I tried two different dates first (2015/10/09 17:40:44) and the second (2015/10/09 14:20:13) .. first one gives me negative value (-4478) .. the second gives me positive value (7572) ! – user3003810 Oct 09 '15 at 15:26
1

I love the Carbon library... https://github.com/briannesbitt/Carbon

$diff = Carbon::now()->diffInSeconds(Carbon::parse('2015/10/09 14:20:00'));
Gravy
  • 12,264
  • 26
  • 124
  • 193