Jump to content

[SOLVED] My age() function.


cordoprod

Recommended Posts

I have a function to output ages from a timestamp.

 

// output age
function age($timestamp) {
$ageTime = $timestamp; 
$t = time(); 
$age = ($ageTime < 0) ? ( $t + ($ageTime * -1) ) : $t - $ageTime;
$year = 60 * 60 * 24 * 365;
$ageYears = $age / $year;

return floor($ageYears);
}

 

I output it from a timestamp from a birthday.

But the problem is let's say if i output a date  which is 30. But  a couple of days, maybe 4-5 days before the actual 31 birthday it shows 31.

 

Can anyone see what the errors are?

Link to comment
https://forums.phpfreaks.com/topic/146685-solved-my-age-function/
Share on other sites

That is because there are not 365 days in every year, so you cannot simply multiply by that number. There is an error of one day for every 4 years of age.

 

The age of something is defined as the difference in the current year and the DOB year, subtract 1 if the birthday has not occurred in the current year (current month/day is less than the DOB month/day).

 

 

<?php
function year($date)
{
return substr($date, 0, 4); 
} // end of year function

function mmdd($date)
{
return substr($date, 5,5);
} // end of mmdd function

function age($today,$date)
{

return year($today) - year($date) - (mmdd($today) < mmdd($date));
} // end of function age

$today = date("Y-m-d");
$date = "2000-11-01";

echo "DOB: $date, Age: " . age($today,$date) . "<br />";
?>

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.