76

I have a table of users in sql and they each have birth dates. I want to convert their date of birth to their age (years only), e.g. date: 15.03.1999 age: 14 and 15.03.2014 will change to age: 15

Here I want to show the date of the user:

if(isset($_GET['id']))
{
    $id = intval($_GET['id']);
    $dnn = mysql_fetch_array($dn);
    $dn = mysql_query('select username, email, skype, avatar, ' .
        'date, signup_date, gender from users where id="'.$id.'"');
    $dnn = mysql_fetch_array($dn);
    echo "{$dnn['date']}";
}
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
PHPupil
  • 785
  • 1
  • 7
  • 10
  • possible duplicate of [Calculate Age in MySQL (InnoDb)](http://stackoverflow.com/questions/5773405/calculate-age-in-mysql-innodb) – John Conde Oct 22 '13 at 14:49
  • presumably your dates are stored using a date data type? – Strawberry Oct 22 '13 at 14:49
  • 2
    there are plenty of 'calculate age' answers out there. Google is a mighty tool! But by the way: Don't use mysql_* functions. Use PDO or MySQLi – Patrick Manser Oct 22 '13 at 14:49
  • Get current date/time and subtract the converted one from database...then convert it back to number of years, use strtotime() and date() with proper formatting. – Bud Damyanov Oct 22 '13 at 14:50
  • Isn't it amazing that no one's ever had to do this before. – Strawberry Dec 30 '13 at 11:28
  • Is this a MySQL problem, or a PHP problem? Also, be warned that the given query is highly vulnerable for SQL injection. Have a look at prepared statements to avoid getting hacked – Nico Haase May 04 '23 at 15:39

10 Answers10

217

PHP >= 5.3.0

# object oriented
$from = new DateTime('1970-02-01');
$to   = new DateTime('today');
echo $from->diff($to)->y;

# procedural
echo date_diff(date_create('1970-02-01'), date_create('today'))->y;

demo

functions: date_create(), date_diff()


MySQL >= 5.0.0

SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age

demo

functions: TIMESTAMPDIFF(), CURDATE()

Community
  • 1
  • 1
Glavić
  • 42,781
  • 13
  • 77
  • 107
8

Got this script from net (thanks to coffeecupweb)

<?php
/**
 * Simple PHP age Calculator
 * 
 * Calculate and returns age based on the date provided by the user.
 * @param   date of birth('Format:yyyy-mm-dd').
 * @return  age based on date of birth
 */
function ageCalculator($dob){
    if(!empty($dob)){
        $birthdate = new DateTime($dob);
        $today   = new DateTime('today');
        $age = $birthdate->diff($today)->y;
        return $age;
    }else{
        return 0;
    }
}
$dob = '1992-03-18';
echo ageCalculator($dob);
?>
googli.us
  • 89
  • 1
  • 2
8

Very small code to get Age:

<?php
    $dob='1981-10-07';
    $diff = (date('Y') - date('Y',strtotime($dob)));
    echo $diff;
?>

//output 35
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
easycodingclub
  • 323
  • 3
  • 5
  • 11
    How did this get 11 votes? A person's age depends on the day and month of the year as well. – Nick Bedford Jun 28 '17 at 04:31
  • 2
    Your method is incorrect if person have DOB ex. 13-10-1991 and current month is July then the age is 27 which is wrong. The person age is 26 till the current month is equal to or greater then the DOB month. – Shaan Ansari Oct 01 '18 at 06:56
5
$hours_in_day   = 24;
$minutes_in_hour= 60;
$seconds_in_mins= 60;

$birth_date     = new DateTime("1988-07-31T00:00:00");
$current_date   = new DateTime();

$diff           = $birth_date->diff($current_date);

echo $years     = $diff->y . " years " . $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $months    = ($diff->y * 12) + $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $weeks     = floor($diff->days/7) . " weeks " . $diff->d%7 . " day(s)"; echo "<br/>";
echo $days      = $diff->days . " days"; echo "<br/>";
echo $hours     = $diff->h + ($diff->days * $hours_in_day) . " hours"; echo "<br/>";
echo $mins      = ($diff->h * $minutes_in_hour) + ($diff->days * $hours_in_day * $minutes_in_hour) . " minutest"; echo "<br/>";
echo $seconds   = ($diff->h * $minutes_in_hour * $seconds_in_mins) + ($diff->days * $hours_in_day * $minutes_in_hour * $seconds_in_mins) . " seconds"; echo "<br/>";
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Shailesh Sonare
  • 2,791
  • 1
  • 18
  • 14
0

For a birthday date with format Date/Month/Year

function age($birthday){
 list($day, $month, $year) = explode("/", $birthday);
 $year_diff  = date("Y") - $year;
 $month_diff = date("m") - $month;
 $day_diff   = date("d") - $day;
 if ($day_diff < 0 && $month_diff==0) $year_diff--;
 if ($day_diff < 0 && $month_diff < 0) $year_diff--;
 return $year_diff;
}

or the same function that accepts day, month, year as parameters :

function age($day, $month, $year){
 $year_diff  = date("Y") - $year;
 $month_diff = date("m") - $month;
 $day_diff   = date("d") - $day;
 if ($day_diff < 0 && $month_diff==0) $year_diff--;
 if ($day_diff < 0 && $month_diff < 0) $year_diff--;
 return $year_diff;
}

You can use it like this :

echo age("20/01/2000");

which will output the correct age (On 4 June, it's 14).

Subin
  • 3,445
  • 1
  • 34
  • 63
0

declare @dateOfBirth date select @dateOfBirth = '2000-01-01'

SELECT datediff(YEAR,@dateOfBirth,getdate()) as Age

JH_
  • 406
  • 1
  • 4
  • 15
YATHI
  • 27
  • 3
0
 $dob = $this->dateOfBirth; //Datetime 
        $currentDate = new \DateTime();
        $dateDiff = $dob->diff($currentDate);
        $years = $dateDiff->y;
        $months = $dateDiff->m;
        $days = $dateDiff->d;
        $age = $years .' Year(s)';

        if($years === 0) {
            $age = $months .' Month(s)';
            if($months === 0) {
                $age = $days .' Day(s)';
            }
        }
        return $age;
Rutendo
  • 39
  • 2
-1

I hope you will find this useful.

$query1="SELECT TIMESTAMPDIFF (YEAR, YOUR_DOB_COLUMN, CURDATE()) AS age FROM your_table WHERE id='$user_id'";
$res1=mysql_query($query1);
$row=mysql_fetch_array($res1);
echo $row['age'];
-1
$getyear = explode("-", $value['users_dob']);
$dob = date('Y') - $getyear[0];

$value['users_dob'] is the database value with format yyyy-mm-dd

mnille
  • 1,328
  • 4
  • 16
  • 20
Tayyab Hayat
  • 815
  • 1
  • 9
  • 22
-3

To Calculate age from Date of birth used used query like this.

'SELECT username, email, skype, avatar, TIMESTAMPDIFF(YEAR, date, CURDATE()) AS age, signup_date, gender FROM users WHERE id="'.$id.'"';


if(isset($_GET['id']))
{
    $id = intval($_GET['id']);

    $dn = mysql_query('select username, email, skype, avatar, TIMESTAMPDIFF(YEAR, date, CURDATE()) AS age, signup_date, gender from users where id="'.$id.'"');

    $dnn = mysql_fetch_array($dn);

    echo $dnn['age'];
}

Note: don't use reserved keywords column name.

Shaan Ansari
  • 510
  • 6
  • 10