almost a beginner almost a beginner - 1 year ago 40
PHP Question

Number of days between two dates doesn't produce right results

Having some issues with calculating number of days between two dates, I have already examined other threads related to this question and couldn't solve my problem.

I'm using this PHP code:

while($row = $result->fetch_assoc()) {
$now = strtotime(date("Y-m-d"));
$to = strtotime($row["pickupdate"]);
//$days = 0;
$days = $to - $now;

if ($days <= 5 && $days >= 0)
echo "<table style='border: solid 1px black;'>...

In my database, I have four "pickupdate"s that are within the range of the if condition, but when I run the query and display the result, I only get two.

I get the same two outputs, which means, it only finds 0 days, but not 1 and 2 days, which I have setup in the database.

Dates in the database within the range:

  • 2016-06-11

  • 2016-06-09

  • 2016-06-09

  • 2016-06-12

So why isn't 11th and 12th of this month displayed when clearly they're within the range of the if statement?

I have changed the if statement to:

if ($days >= 0 && $days <= 100)

I still get the same exact two results,

Any help or direction would be appreciated, thanks.

Answer Source

As stated in comments you are subtracting strings. It won't work.

$days = (strtotime($to) - strtotime($now))/86400;