简体   繁体   中英

Trying to calculate using (current php date - mySQL timestamp = difference in days)

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 

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM