Search code examples
phpdatetimesubtraction

Php subtract two dates


I am getting $status_date from mysql database and when I echo $status_date it looks like this -> 2016-01-08 22:18:14. I am setting $now and when I echo it looks like this -> 2016-01-08 22:43:27. I want to subtract $status_date from $now. Here is my code:

$now = date("Y-m-d H:i:s");  
$status_date = date("Y-m-d H:i:s",strtotime($row['status_date']));
$x = $now-$status_date;

$x returns this -> 0

Why is it not subracting?


Solution

  • Dates don't subtract like that. Convert both dates to time, subtract, and convert back to a date.

    $now = strtotime(date("Y-m-d H:i:s"));
    $status_date = strtotime($row['status_date']);
    $x = date($now-$status_date);
    

    However if you're trying to get the time between the dates consider the moment library.

    https://github.com/fightbulc/moment.php