I have a function that calculates the number of days left for a product listing to expire.When i run the code below I am getting floating point numbers e.g 3.4722222222222E-5
$days_left = date('d', strtotime($this->expiry_date) - strtotime($date)) / (60 * 60 * 24);
$this->days_left = $days_left;
When I round of the result
(round)$this->days_left
a keep getting 0
strtotime($this->expiry_date) - strtotime($date)
gives you the time difference in seconds.
date('d', $time)
would give you the day part of that $time
, removing any month/year part. And you divide number of seconds per day in that figure which is already a day number?? Floating point would result, obviously, as computers just blindly do the division.
Instead, ditch the date
function to get number of days, but divide your time (in seconds) with number of seconds in a day:
$days_left = (strtotime($this->expiry_date) - strtotime($date)) / (60 * 60 * 24);
And you don't "type cast" to round
which doesn't exist. As per comments, do round($this->days_left)
If you want to do calculations with dates correctly, you should use DateTime
objects. The difference between dates (duration of something) should then be rendered as a DateInterval
object, which gives exact differences.