Jump to content

date of birth to days old in php


kevinkhan

Recommended Posts

You can do, not the best solution, but it works.

 

return floor( (time() – strtotime($dateofbirth ) ) / 31556926);

 

Also I tried to see what Google would return, you should try it more often :)

 

http://stackoverflow.com/questions/3380990/php-calculate-persons-current-age

 

Yeah and writing such a function will probably never be 100% accurate since there is not same amount of days in every year, not same amount of hours in every day (swaps between summer and winter time) etc. Either way writing the function would probably be huge pain in the ass.

function calculate_age($birthday) {
    $time = strtotime($birthday);
    if ($time === FALSE || $time === -1) return FALSE;
    
    $a = idate('Y') - idate('Y', $time);
    $b = mktime(0, 0, 0, idate('n', $time), idate('j', $time), idate('Y'));
    if (time() < $b) --$a;
    return $a;
}

print calculate_age('1986-09-05').PHP_EOL; // 24
print calculate_age('1986-08-05').PHP_EOL; // 24
print calculate_age('1986-07-05').PHP_EOL; // 25

 

Just an idea. I prefer phpSensei's solution.

I am in the process of writing up a small article on how to do this directly with mysql SQL in a query.  So if you have the birthdate in a mysql DATE type column, this query will get you a person's age, based on their birthdate.

 

This query assumes a table named "bday", with the birthdate column named "bdate".  You would need to adjust for your table and structure accordingly.  You'd want to add an appropriate WHERE clause to get only one row as well.

 

SELECT YEAR(CURDATE()) - YEAR(bdate) - 
IF(STR_TO_DATE(CONCAT(YEAR(CURDATE()), '-', MONTH(bdate), '-', DAY(bdate)) ,'%Y-%c-%e') >= CURDATE(), 1, 0) 
AS age FROM bday;

 

 

SELECT YEAR(CURDATE()) - YEAR(bdate) - 
IF(STR_TO_DATE(CONCAT(YEAR(CURDATE()), '-', MONTH(bdate), '-', DAY(bdate)) ,'%Y-%c-%e') >= CURDATE(), 1, 0) 
AS age FROM bday;

 

We think alike! ;) Is it intended to calculate this for everyone in the bday table?

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.