Jump to content

date of birth to days old in php


kevinkhan

Recommended Posts

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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;

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.