TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   Age Calculation Script (http://www.talkphp.com/general/3234-age-calculation-script.html)

 Jako 08-12-2008 07:44 PM

Age Calculation Script

I have a script I use to calculate the age of users in my database

PHP Code:

``` <? function calculate_age (\$month, \$day, \$year) { \$ageTime = mktime(0, 0, 0, \$month, \$day, \$year); // Get the person's birthday timestamp \$t = time(); // Store current time for consistency \$age = (\$ageTime < 0) ? ( \$t + (\$ageTime * -1) ) : \$t - \$ageTime; \$year = 60 * 60 * 24 * 365; \$ageYears = \$age / \$year; \$actual=floor(\$ageYears); return \$actual; } ?> ```
When I input something like 12-6-1989 it returns an age of 18 which is correct.

But when I was inputing an age of 12-16-1899 it returns an age of 38. Any idea why?

 buggabill 08-13-2008 01:47 PM

The Unix epoch which mktime uses starts on January 1, 1970. Wikipedia Article

Someone born in 1970 would be 38 today. :-)

You will need to some modifications to that script to get accurate ages before that date.

You could do something like the following:
php Code:
`<?phpfunction calculate_age (\$month, \$day, \$year) {     \$year_diff = date("Y") - (\$year);    \$month_diff = date("m") - (\$month);    \$day_diff = date("d") - (\$day);        if (\$month_diff < 0) {        \$year_diff--;    }    elseif (\$month_diff == 0 && \$day_diff < 0) {        \$year_diff--;    }    return \$year_diff;}?>`

 delayedinsanity 08-13-2008 06:40 PM

You can still use mktime to get accurate ages.

PHP Code:

``` function getAge (\$month, \$day, \$year){    \$now = mktime( 0, 0, 0, date("n"), date("j"), date("Y") );    \$then = mktime( 0, 0, 0, \$month, \$day, \$year );    \$age = floor(((((\$now - \$then) / 60) / 60) / 24) / 365.25);    return \$age;}  ```

 buggabill 08-14-2008 12:47 PM

Quote:
 Originally Posted by delayedinsanity (Post 17741) You can still use mktime to get accurate ages. PHP Code: ``` function getAge (\$month, \$day, \$year) {     \$now = mktime( 0, 0, 0, date("n"), date("j"), date("Y") );     \$then = mktime( 0, 0, 0, \$month, \$day, \$year );     \$age = floor(((((\$now - \$then) / 60) / 60) / 24) / 365.25);     return \$age; }  ```
I stand partially corrected.

Take a look at the notes section for mktime.

Quote:
 Caution Before PHP 5.1.0, negative timestamps were not supported under any known version of Windows and some other systems as well. Therefore the range of valid years was limited to 1970 through 2038.
You need to be really careful if what you're writing has any chance of being used on systems like they describe.

 All times are GMT. The time now is 02:49 PM.