(Looks like something's wrong with my environment / system. Am analyzing it currently. Every logical answer was tried and it failed. So, will report back once I have more to share. Thanks for the answers!)
I have written some simple PHP code to calculate the duration between two dates, and do some basic arithmetic, to calculate some percentage value.
I am at a loss of clues on why this is not working! Seems to me that a variable is treated as an integer on one line and a string on another.
$start_DT = new DateTime($startdate); // e.g. 2011-06-07
$end_DT = new DateTime($enddate); // e.g. 2011-06-14
$today_DT = new DateTime("now"); // 2011-06-09
$duration = date_diff($end_DT, $start_DT)->d;
$days_remaining = date_diff($end_DT, $today_DT)->d;
echo $days_remaining; // This outputs a value of "4" in my specific case
echo $duration; // This outputs a value of "7" for my specific case.
$percentage_dur_complete = $days_remaining / $duration;
echo $percentage_dur_complete; // This gives a value of NAN
// This line says that I am dividing my zero, to imply that
// $duration might be a string.
$percentage_dur_complete = $days_remaining / (float) $duration;
Am I missing something basic? I am a relative newbie (2 months) to PHP. I really hope (with the risk of appearing stupid) that there's something I've missed out.
Thanks!
PHP | intdiv() Function. intdiv stands for integer division. This function returns the integer quotient of the division of the given dividend and divisor. This function internally removes the remainder from the dividend to make it evenly divisible by the divisor and returns the quotient after division.
The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned. For integer division, see intdiv().
The intdiv() is PHP mathematical function of PHP, which is used to calculate integer division. It returns the integer quotient of the division of dividend by divisor.
The fmod() function returns the remainder (modulo) of x/y.
try
$percentage_dur_complete = (int)$days_remaining / (int)$duration;
EDIT: This works for me...
<?php
$startdate = '2011-06-05';
$enddate = '2011-06-12';
$today_DT = new DateTime("now");
$start_DT = new DateTime($startdate); // e.g. 2011-06-07
$end_DT = new DateTime($enddate);
$duration = date_diff($end_DT, $start_DT)->d;
$days_remaining = date_diff($end_DT, $today_DT)->d;
var_dump ($duration);
var_dump ($days_remaining);
$percentage_dur_complete = $days_remaining / $duration *100;
echo ($percentage_dur_complete);
?>
If it doesnt for you, it is most definitely an issue with your PHP installation/version!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With