Results 1 to 5 of 5
Dec 5, 2009, 00:53 #1
- Join Date
- Dec 2009
- 0 Post(s)
- 0 Thread(s)
Tidy Date-of-birth to Age conversion code
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!
Dec 5, 2009, 07:41 #2
- Join Date
- Jul 2002
- Toronto, Canada
- 63 Post(s)
- 3 Thread(s)
Dec 5, 2009, 14:39 #3
- Join Date
- Sep 2005
- Sydney, NSW, Australia
- 25 Post(s)
- 1 Thread(s)
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.
Dec 5, 2009, 17:12 #4
Or you could use the DateTime/DateInterval classes
echo DateTime::createFromFormat("!d/m/Y", "06/12/1968")
->format("%y years old");
Software Developer and PHP Manual Author.
Dec 7, 2009, 14:44 #5PHP Code:
$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))