0

I've looked through the questions that are on the site and I think the problem that I'm encountering is a bit more in depth. I've tried using the difftime() function but it results in 0 for me.

So far This is what I've done

$currentDate =  time();
//echo $printDate;
//echo $currentDate;
$editedDate = date("Y-m-d ", strtotime($printDate)); 
$editedCurrentTime = date("Y-m-d ", $currentDate); 


echo "$editedDate </br>";
echo "$editedCurrentTime </br>";

$timeDiff = ($editedCurrentTime - $editedDate);
echo "$timeDiff </br>";
$numberDays = floor($timeDiff/(60*60*24));

I'm first saving the time(); into currentDate, printDate has the date the entry was put into the database. Both are formatted and the echo prints out correctly like it should. The third echo is where the subtraction becomes a 0 for some reason. When I tried a strtotime($currentDate) the echo for editedCurrentTime became 1970-01-01. I'm guessing this is a small problem having to do with the fact that they are in different formats but it's still stumping me. Any help would be greatly appreciacted.

Here is a snippet of the output:

2012-08-01 
2012-08-08 
0 
2012-08-01 
2012-08-08 
0 
2012-08-01 
2012-08-08 
0 
2012-08-02 
2012-08-08 
0 
user1058359
  • 183
  • 1
  • 2
  • 13

2 Answers2

2

The date() function returns a string based on the format you put into it. You cannot execute arithmetic operations on strings.

What you should do is that you first calculate the difference of the timestamp (integer) you retrieve from the database and time() and only then you format this difference with the date() function.

(Note: you should store date and time in the unix epoch integer format in the database too.)

Whisperity
  • 3,012
  • 1
  • 19
  • 36
  • Hey, so I've tried your method of subtracting the time() from the timestamp but that too returns the wrong result the difference is just the current day and the $numberDays is still 0 after the calculation. – user1058359 Aug 08 '12 at 14:01
  • If `$printDate` is a timestamp already, try `$foo = time() - $printDate`. If not, you need to first convert it to be a timestamp. Is the data stored good originally in the database? – Whisperity Aug 08 '12 at 14:03
  • $printDate is taken directly from the database, which part would I need to convert to a timestamp? – user1058359 Aug 08 '12 at 14:11
  • Depends how it is stored in the database. If it was a `time()` output when it was stored, there is no need to convert anything. Could you show some example raw data? – Whisperity Aug 08 '12 at 14:27
  • This is a DB entry for the TIMESTAMP "2012-08-01 16:01:28" – user1058359 Aug 08 '12 at 16:03
1

Are you looking for this? How to calculate the difference between two dates using PHP

Community
  • 1
  • 1
Drew
  • 11
  • 1
  • No, this one takes two strings, there's plenty of code out there for that I'm looking specifically at the timestamp format in mySQL and a way to subtract the current date - timestamp – user1058359 Aug 08 '12 at 16:33