1

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?

  • Because the two variables you are trying to substract are just strings. You cannot substract one string from another, PHP will cast them to 0. Check the comment above, your question is duplicate of another question. – Firat Akandere Jan 08 '16 at 22:52

3 Answers3

3

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

micah
  • 7,596
  • 10
  • 49
  • 90
1

You can also use something like:

$now = new DateTime();
$status_date = new DateTime($row['status_date']);
$diff = $now->diff($status_date);

Then you can use any of the dateInterval properties or functions with $diff.

Documentation: http://php.net/manual/es/datetime.diff.php http://php.net/manual/es/class.dateinterval.php

j2e
  • 556
  • 3
  • 10
0

according to http://php.net/manual/en/datetime.diff.php

check this code i wrote here : https://eval.in/499594

<?php 

$strStart = '2015-01-08 22:18:14'; // status  date
$strEnd = 'now';  

$dteStart = new DateTime($strStart); 
$dteEnd   = new DateTime($strEnd); 

$dteDiff  = $dteStart->diff($dteEnd); 

print $dteDiff->format("%Y-%m-%d %H:%I:%S"); 

thre result is smth like : 01-0-0 00:38:42

Mojtaba Hn
  • 457
  • 2
  • 10