Im trying to take 2 dates and subtract them from each other
$now = date('2014-07-17');
$due = date('2014-07-20');
$diff = $now - $due;
$timeRemaining = floor($diff/(60*60*24);
This just returns 0 everytime when it should be 3
date()
takes a string format and Unix Timestamp as a parameter, not just a literal date string. So both calls to date()
is returning the original value to you since both are invalid arguments. Type juggling due to the subtraction of strings returns 2014
for both of those variables and the result then is they are equal.
Use strtotime()
instead which returns the timestamp you are expecting and can do your date math with.
Also, you need to put the later date first if you want a positive integer as a result.
$now = strtotime('2014-07-17');
$due = strtotime('2014-07-20');
$diff = $due - $now;
$timeRemaining = floor($diff/(60*60*24);
You need to use strtotime
, not date
. And you need to reverse your subtraction formula - the earlier date($now
) should be subtracted from the future date($due
).
$now = strtotime('2014-07-17');
$due = strtotime('2014-07-20');
$diff = $due - $now;
$timeRemaining = floor($diff/(60*60*24));
You're subtracting two strings, which get type juggled to the integer value 2014
for each string, which will of course return 0
.
$now = (int) date('2014-07-17'); // Will make $now = 2014
Here's a way to do it (but I'd recommend using DateTime
objects instead):
$now = strtotime('2014-07-17');
$due = strtotime('2014-07-20');
$diff = $due - $now; // Notice how you had your original equation backwards
$timeRemaining = floor($diff/(60*60*24));
Here's how to do it with DateTime
objects:
$now = new DateTime('2014-07-17');
$due = new DateTime('2014-07-20');
$diff = $due->sub($now);
$timeRemaining = $diff->format('%d');