Calculating Age From Date of Birth In PHP

I imagine it’s a fairly common task to calculate an age in years from a date of birth. However most of the solutions I’ve seen either seem to be unnecessarily complicated or else fail to take in into account leap years or the current month and date as well as year. The following function is very fast and pretty simple.

shutterstock_95580649

function age_from_dob($dob) {
    list($d,$m,$y) = explode('-', $dob);
    if (($m = (date('m') - $m)) < 0) {
        $y++;
    } elseif ($m == 0 && date('d') - $d < 0) {
        $y++;
    }
    return date('Y') - $y;
}

 

It expects a date of birth in the format “DD-MM-YYYY”, however this can be modified by changing the order of the variables in the list function, for example to change to “MM-DD-YYYY” you would just edit like so:

list($m,$d,$y) = explode('-', $dob);

 

One note to bear in mind – it is tempting to accept a string in any valid format and parse it with strtotime. This will work, but because it relies upon a Unix timestamp, it will not work for dates before 1 January 1970. If this is not an issue for you, the following function can be used instead, and saves having to massage dates into the required format beforehand:

function age_from_dob($dob) {
    $dob = strtotime($dob);
    $y = date('Y', $dob);    
    if (($m = (date('m') - date('m', $dob))) < 0) {
        $y++;
    } elseif ($m == 0 && date('d') - date('d', $dob) < 0) {
        $y++;
    }   
    return date('Y') - $y; 
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s