2

I'm trying to get this code to calculate the age from a field in a form.

<?php
   $birthDate = "$dob";

   $birthDate = explode("-", $birthDate);

   $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])-1):(date("Y")-$birthDate[2]));
   echo "Age is: ".$age;
?>

but i can't get it to use the format of the input field which is YYYY-MM-DD.

If i change $dob to a date in the eu standard format that PHP uses it works like a charm.

Is there some easy way to correct this?

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
user2154907
  • 23
  • 1
  • 3
  • Possible duplicate of http://stackoverflow.com/questions/4060004/calculate-age-in-javascript – Maen Mar 11 '13 at 15:01

3 Answers3

1

Always be careful with date notation (ie. order of years, months and days).

This is working (original code adapted):

<?php
$birthDate = "1984-05-21";

$birthDate = explode("-", $birthDate);

$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[2], $birthDate[1], $birthDate[0]))) > date("md") ? ((date("Y")-$birthDate[0])-1):(date("Y")-$birthDate[0]));
echo "Age is: ".$age;
?>
unicorn80
  • 1,107
  • 2
  • 9
  • 15
0

Use the DateTime::diff function

Example

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2013-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%y years');
?>
huysentruitw
  • 27,376
  • 9
  • 90
  • 133
0

Use strtotime($dob) to get a timestamp. Then to calculate age in the human way:

list($dob_year, $dob_date) = explode('-', date('Y-md', strtotime($dob)));
list($cur_year, $cur_date) = explode('-', date('Y-md'));

$age = $cur_year - $dob_year - ($dob_date >= $cur_date ? 0 : 1);
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309