Karl Rixon

Calculating Age From Date of Birth In PHP

with 3 comments

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
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:

1
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
   
}

Written by Karl

May 27th, 2009 at 12:39 pm

Posted in PHP

3 Responses to 'Calculating Age From Date of Birth In PHP'

Subscribe to comments with RSS or TrackBack to 'Calculating Age From Date of Birth In PHP'.

  1. 1
    2
    3
    function age_from_dob($dob) {
        return floor((time() - strtotime($dob)) / 31556926);
    }

    Just add $dob validation.

    Chris

    10 Dec 09 at 5:18 pm

  2. Nice solution Chris, thanks!

    Karl

    11 Dec 09 at 10:16 am

  3. Really working well. Great job. Thanks for time saving, the precious thing in the world

    kashif wasim

    1 Jan 10 at 7:54 pm

Leave a Reply