Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Get difference between two datetime in seconds

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);
?>
like image 682
user3003810 Avatar asked Dec 08 '22 01:12

user3003810


2 Answers

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
like image 194
Pedro Lobito Avatar answered Dec 11 '22 12:12

Pedro Lobito


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

$diff = Carbon::now()->diffInSeconds(Carbon::parse('2015/10/09 14:20:00'));
like image 41
Gravy Avatar answered Dec 11 '22 12:12

Gravy