SitePoint Sponsor |
|
User Tag List
Results 1 to 5 of 5
-
Dec 5, 2009, 00:53 #1
- Join Date
- Dec 2009
- Posts
- 38
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
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!
-
Dec 5, 2009, 07:41 #2
- Join Date
- Jul 2002
- Location
- Toronto, Canada
- Posts
- 39,347
- Mentioned
- 63 Post(s)
- Tagged
- 3 Thread(s)
accurate to within 1 second? sorry, no
plug in a birthdate of 2008-12-07 and see what you get
-
Dec 5, 2009, 14:39 #3
- Join Date
- Sep 2005
- Location
- Sydney, NSW, Australia
- Posts
- 16,875
- Mentioned
- 25 Post(s)
- Tagged
- 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.
Stephen J Chapman
javascriptexample.net, Book Reviews, follow me on Twitter
HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
<input name="html5" type="text" required pattern="^$">
-
Dec 5, 2009, 17:12 #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");
-
Dec 7, 2009, 14:44 #5PHP 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;
}
Bookmarks