note 31220 deleted from function.mktime by sniper
| From: | sniper@php.net | Date: | Tue, 04 Nov 2003 13:10:45 +0000 |
| Subject: | note 31220 deleted from function.mktime by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-59873@lists.php.net to get a copy of this message | ||
Note Submitter: advertisement@freenet.de
----
Be careful when using D. Heldens way to calculate one's age:
[...]
$age=intval(($nowdate-$birthday)/(60*60*24*365));
[...]
It does not pay attention to leapyears and may return wrong results a few days before the actual
birthday.
You may want to use this function instead:
function numOfLeapDays($from, $to) {
if ( (checkdate(2,29,date("Y",$from))) AND ($from >
mktime(0,0,0,2,29,date("Y",$from))) ) {
$fromYear = date("Y",$from)+1;
}
else {
$fromYear = date("Y",$from);
}
if ( (checkdate(2,29,date("Y",$to))) AND
($to<mktime(0,0,0,2,29,date("Y",$to))) ) {
$toYear = date("Y",$to)-1;
}
else {
$toYear = date("Y",$to);
}
$numOfLeapDays = 0;
for($i=$fromYear; $i<=$toYear; $i++) {
if ((($i % 4) == 0) AND ((($i % 400) == 0) OR (($i % 100) <>0))) $numOfLeapDays++;
}
return $numOfLeapDays;
}
function age($born) {
$now = mktime(0,0,0,date("m"),date("d"),date("Y"));
$leapDays = numOfLeapDays($born, $now);
$age = intval( (( ($now - $born)/(60*60*24) )-$leapDays)/365 );
return $age;
}
age(mktime(0,0,0,2,26,1982)); will return 21 (on 04/14/03)
On my server it seems to work from ~1900 to 2037; you may have a different range on yours...
Hope it helps!!
Robin Wielpuetz