Home > Back-end >  DateTime class and $obj->diff() issue calculating age
DateTime class and $obj->diff() issue calculating age

Time:12-09

On a family genealogy website (php/MySQL), people having their birthday today are on welcome page, with mention of their age

I'm using this code, in which $ddn is the date of birth (DateTime object) :

$datenow = new DateTime();
$age = $ddn->diff($datenow)->format('%Y');

It's usually ok, with right age.

But I discovered today that my grand-Pa', born 100 years ago on 3th dec. 1922, is said to be 99 years old.

I tried to change date of birth to different values, and got these calculated ages :

Date of birth (Y-m-d) Age
1952-12-03 70
1942-12-03 80
1941-12-03 81
1940-12-03 82
1939-12-03 82
1938-12-03 83
1932-12-03 89
1922-12-03 99

Everything is ok until 1940-12-03, and gets wrong when date of birth is earlier.

What happens, between 1939 and 1940, so that every calculated age turns wrong for people born before 1940 ?

How to fix it ?

Thanks

CodePudding user response:

maybe you can check your server date time, I've tried it on my local computer, 1939-12-03 return 83 and 1940-12-03 return 82.

If the server date time was correct, please check on your PHP configuration for the timezone, or if you were using Laravel, you can check it on config/app.php.

CodePudding user response:

Thanks for your answer

I'm running UwAmp as local server on Windows for coding, and online website is hosted on a Linux server (Ionos 1&1). The problem occurs on both servers. So it doesn't seem to be a problem of php configuration.

But you're right with timezone concern : in my php code, I tried to change

date_default_timezone_set('Europe/Paris');

to

date_default_timezone_set('UTC');

...and that fixed it.

So that's ok for me, but... does anyone know what's wrong with Europe/Paris timezone ?

  • Related