# Thread: Tidy Date-of-birth to Age conversion code

1. ## Tidy Date-of-birth to Age conversion code

Hello,

DoB to years:

<?
//calculate years of age (input string: \$DateOfBirth = YYYY-MM-DD)

\$age = strtotime(date("Y-m-d")) - strtotime(\$DateOfBirth);
\$age = round( \$age/31556926);
echo \$age,"<br />";
?>

i have updated it to account for the fact that an average year has 365.242199 days in it, with a result of 18 hours more accuracy per century.

it is accurate to 1 second every 100 years, although it will be off by half a day on every birthday due to the gap year being every 4th year. it is more accurate for celestial time of your birthday to the second. it depends if you code by celestial or earth time.

-=A VERY BORING CALCULATION EXPLANATION FOLLOWS TO EXPLAIN THE FEW SECONDS BETTER ACCURACY!=-

the long number is the number of seconds in a year (60x60x24x365.25)
365.25 days per year is 31557600
365.242199 days per year is 31556925.995

So in case your code is still running in 100 years, you would have about 18 hours more accuracy, or 11 minutes per year.

Sorry i am enjoying being a dork once again! i love this programming stuff i havent done any coding since i learnt dragon naturally speaking scripts 5 years ago! lots of catching up to do in geekiness here!

2. accurate to within 1 second? sorry, no

plug in a birthdate of 2008-12-07 and see what you get

3. To get the age accurately you need to subtract the year of birth from the current year and then if the current month-day is not less than the birth month-day then add one to the result.

4. Or you could use the DateTime/DateInterval classes

PHP Code:
``` echo DateTime::createFromFormat("!d/m/Y", "06/12/1968")      ->diff(new DateTime("today"))      ->format("%y years old");  ```

5. PHP Code:
``` function age(\$date_formatted){         \$iTimestamp =  strtotime(\$date_formatted);                  // See http://php.net/date for what the first arguments mean.         \$iDiffYear  = date('Y') - date('Y', \$iTimestamp);         \$iDiffMonth = date('n') - date('n', \$iTimestamp);         \$iDiffDay   = date('j') - date('j', \$iTimestamp);                  // If birthday has not happen yet for this year, subtract 1.         if (\$iDiffMonth < 0 || (\$iDiffMonth == 0 && \$iDiffDay < 0))         {             \$iDiffYear--;         }                      return \$iDiffYear;     }  ```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•