On the fly date difference calculation

dimoss

Well-Known Member
Hi

I have a calc element in order to calculate the difference between two dates in years, months, days:

PHP:
$date1 = '{fab_tekna___dob}';
$date2 = date('Y-m-d h:i:s');
 
$diff = abs(strtotime($date2) - strtotime($date1));
 
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24) / (60*60*24));
 
return printf("%d years, %d months, %d days\n", $years, $months, $days);

I have put 'Calc on save' to No because I want to calculate on the fly for each row.

It works ok BUT there is strange problem and the result is not shown on the correct position (last list column) but on the top and instead of this I get just a number in each list row!!

See the screenshot:

Screenshot_1.jpg

Any ideas??

Thanks.
 
Solved!

I changed the calculation using DateTime and DateInterval objects like this:

Code:
$date1 = new DateTime('{fab_tekna___dob}');
$date2 = new DateTime(date('Y-m-d h:i:s'));
$interval = $date1->diff($date2);
{return $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";}

....and worked!

I post it in case someone need it.
 
Sorry I didn't get to this one earlier to save you some heartache and time, but yeah ... date calculations are pretty much always easier to do using PHP's native features, rather than doing it by steam yourself.

-- hugh
 
Hi Sophist

Because for some reason I don't know, if I don't use the brackets it doesn't work in my app.
 
We are in need of some funding.
More details.

Thank you.

Members online

Back
Top