This topic is locked

Expiration Date

7/10/2013 10:06:31 PM
PHPRunner General questions
O
onlline author

Hi !
I used the following code but the calculation is wrong

PHPRunner 6.2
//////Init Code
if ($value > NOW())

{

$firstTime=strtotime($value);

$lastTime=strtotime(NOW());

// perform subtraction to get the difference (in seconds) between times

$diff=$firstTime-$lastTime;

// convert

$years = floor($diff / (365606024));

$months = floor(($diff - $years
365606024) / (30606024));

$days = floor(($diff - $years 365606024 - $months30606024)/ (606024));

//

$time_left = "";

if ($years > 0 ) { $time_left .= $years."Years ";}

if ($months > 0 ) { $time_left .= $months."Months ";}

if ($days > 0 ) { $time_left .= $days."Days ";}

$value .= "<br/><STRONG><FONT COLOR='black'>Expires in<br/>";

$value .= $time_left;

$value .= "</STRONG></FONT>";

}

else

{
// Show an Expired message below the date in red.

$value .= "<br/><font color='red'>Expired</font>";

}


Thanks in advanced

C
cgphp 7/11/2013

The calculation is wrong because the code above is an approximation. For example, there are months with 30 days and months with 31 days but you are considering only the ones with 30 days.

O
onlline author 7/11/2013



The calculation is wrong because the code above is an approximation. For example, there are months with 30 days and months with 31 days but you are considering only the ones with 30 days.


Cristian,
shows 5 years and 12 months should show 5 years


Thanks in advanced

Sergey Kornilov admin 7/11/2013

You are forgetting the fact that some months have more than 30 days.
Your calculation is incorrect, instead of getting 11 months you get 12 months and this is what makes the end result look wrong.

O
onlline author 7/11/2013



You are forgetting the fact that some months have more than 30 days.
Your calculation is incorrect, instead of getting 11 months you get 12 months and this is what makes the end result look wrong.


it is possible to fix this error?
should show five years 4years + 12months = years 5
or is there another way to calculate the time to expiration?
Thanks in advanced

Sergey Kornilov admin 7/11/2013

Check this article:

http://www.php.net/manual/en/datetime.diff.php
It shows how properly calculate the difference between two dates in months or days.
More examples of formatting the result of date diff:

http://www.php.net/manual/en/dateinterval.format.php