note 31220 added to function.mktime
| From: | advertisement at freenet dot de | Date: | Mon, 14 Apr 2003 12:07:03 +0000 |
| Subject: | note 31220 added to function.mktime | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-46592@lists.php.net to get a copy of this message | ||
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
--
http://www.php.net/manual/en/function.mktime.php
http://master.php.net/manage/user-notes.php?action=edit+31220
http://master.php.net/manage/user-notes.php?action=delete+31220
http://master.php.net/manage/user-notes.php?action=reject+31220