Re: age

From: Date: Mon, 06 Aug 2001 04:53:55 +0000
Subject: Re: age
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-61377@lists.php.net to get a copy of this message
* Jon Yaggie <dmsales@design-monster.com> [010805 16:35]: > does any one know where i can get a script that will convert a > birthdate in to an age. i have one half written however i have > incounter difficulties with dealing with leap years. perhaps soem > one would know the solution . .. or just a premade script is fine This is one of those problems that sounds easy ... until you get into it. It is leap years that make it messy. Try this ... it worked on all the dates I threw at it, and has options for whether you want just the year or a fraction, and the fraction can be decimal or days: function age($birthdate) { // $birthdate can be most any format $bornUnix = strtotime($birthdate); $born = getdate($bornUnix); $todayUnix = time(); $today = getdate(); $last = array('year' => $today['year'], 'mon' => $born['mon'], 'mday'=>$born['mday']); $next = $last; if ($today['mon'] < $born['mon']) { // before birthday $last['year'] -= 1; } elseif ($today['mon'] > $born['mon']) { // after birth month $next['year'] += 1; } else { // in birth month if ($today['mday'] < $born['mday']) { // before birthday $last['year'] -= 1; } elseif ($today['mday'] > $born['mday']) { // after birthday $next['year'] += 1; } else { // happy birthday $next['year'] += 1; } } $age = $last['year'] - $born['year']; // set $yearFraction to TRUE if you want fractional days $yearFraction = TRUE; if ($yearFraction) { // set $yearDecimals to number of decimals desired $yearDecimals = 3; $lastUnix = mktime(0,0,0,$last['mon'],$last['mday'],$last['year']); $nextUnix = mktime(0,0,0,$next['mon'],$next['mday'],$next['year']); $daysThisYear = ($nextUnix-$lastUnix)/(24*60*60); $daysSinceLast = ($todayUnix-$lastUnix)/(24*60*60); if ($yearDecimals > 0) { // give decimal fraction $age += $daysSinceLast/$daysThisYear; $age = number_format($age,$yearDecimals); } else { // give actual fraction $age .= " " . number_format($daysSinceLast,0) . "/" . number_format($daysThisYear,0); } } return $age; } -- Jan Wilson, SysAdmin _/*]; corocom@btl.net Corozal Junior College | |:' corozal.com corozal.bz Corozal Town, Belize | /' chetumal.com & linux.bz Reg. Linux user #151611 |_/ Network, SQL, Perl, HTML

« previous php.general (#61377) next »