PHP - Get difference between two datetime in seconds [duplicate]
Asked Answered
E

2

5

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);
?>
Emarginate answered 9/10, 2015 at 14:31 Comment(1)
Make sure the later date is the first date. Or use abs() to ignore the negative value.Diseur
P
14

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
Pergrim answered 9/10, 2015 at 14:36 Comment(3)
... or Datetime::diff()->format() : php.net/manual/en/datetime.diff.php ... but you get an upvote anyway for using DateTime ;)Doggy
@Doggy that option doesn't provide more than 59 seconds. But I had the same thought initially.Diseur
@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) !Emarginate
L
1

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

$diff = Carbon::now()->diffInSeconds(Carbon::parse('2015/10/09 14:20:00'));
Larrigan answered 9/10, 2015 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.