[BlueOnyx:12825] Re: PHP Date_Diff

Michael Stauber mstauber at blueonyx.it
Fri Apr 12 15:35:21 -05 2013


Hi Richard,

> Now the developer of the software has looked at the problem we have, and
> that is, that if some of the entrants are close to another age category,
> it sometimes puts them in the wrong category as he tells me the
> data_diff function seems to be calculating things incorrectly. On
> previous versions of BO and PHP I guess before the function was built
> in, we had no problems as he used code within his software to do the
> calculation.

Fire the developer. ;-)

Those who program in PHP have learned to avoid the date_diff() function
as it has issues. It's one of the stupid and lazy "solutions" that came
aboard with PHP-5.3.0. Lazy solutions (often bugged!) that offer
"simpler" approaches than the trusted methods that PHP coders have used
successfully in the past decade. I guess that's what you get when you
let the point and click crowd of web designers loose at something that
was supposed to be an attempt at a programming language. ;-)

Now over various PHP versions this bugged date_diff() - and it's parent
DateTime() - produce entirely different results. It also depends on the
timezone you have configured in the php.ini. When the shift over to
daylight saving happens, you get weird results when you cross compute dates.

Even without that: If your script relies on date_diff() it's not really
portable, as you will get odd results depending on system settings and
used PHP versions. So any PHP coder is well advised to not rely on that
function, unless the oddities are acceptable or are compensated otherwise.

You could try another PHP version from http://shop.blueonyx.it like
5.3.23 or 5.4.13 and see what kind or results you get there.

But ideally it would be better if your code would use more reliable and
more robust methods for such calculations.

Now there are many ways to do that. Personally I'd probably do what I
have been doing the last ten years: Use strtotime() to convert two dates
to unix time and then calculate the number of seconds between them.
Which will produce pretty robust and consistent results, regardless of
if you run on Linux, Windows or whatever the PHP version might be.

And it's not necessarily much more complicated, because it can be as
simple as this to avoid usage of date_diff():

<?php
$today = strtotime("2013-04-12 15:25:00");
$myBirthDate = strtotime("1971-05-24 09:48:00");
printf("I'm %d days old.", round(abs($today-$myBirthDate)/60/60/24));
?>

See:

http://stackoverflow.com/questions/13711955/php-date-diff-craziness
http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php
http://php.net/manual/en/dateinterval.format.php
http://www.php.net/manual/en/function.date-diff.php


-- 
With best regards

Michael Stauber



More information about the Blueonyx mailing list