0

Possible Duplicate:
PHP calculate person's current age

I want to find the persons age.

 $time=$row['date_of_birth'];
 $date=explode("-", $time);//gets the date birth from the database and puts it into an array
 $a=getdate();//gets todays date
 $diff_date= gregoriantojd($a["mon"],a["mday"],a["year"] ) - gregoriantojd(date[1],date[2],date[0]);//subtracts the differences between the dates, this is returned in seconds..

The question is whether this is the way to do it? and how do I convert the seconds and convert them to years (as an integer)?!

EDIT: I think that the last line should be this:

 return floor($diff_date /60*60*24*365);
Community
  • 1
  • 1
WithFlyingColors
  • 2,650
  • 4
  • 20
  • 25

4 Answers4

3

Just try with strtotime (converts date string into timestamp):

$time = strtotime($row['date_of_birth']);
$age  = date('Y', $time - time());

echo 'age: ' . $age;
Wesley van Opdorp
  • 14,888
  • 4
  • 41
  • 59
hsz
  • 148,279
  • 62
  • 259
  • 315
1

If $time is supposed to be unix timestamp

$time=$row['date_of_birth'];
$date1 = new DateTime($time);
$date_diff = $date1->diff(new DateTime(), true);
$age = $date_diff->y;
Peter
  • 69
  • 3
0

I think you can make use of the date_diff function in PHP.

Damodaran
  • 10,882
  • 10
  • 60
  • 81
0

1st question: The question is whether this is the way to do it?

No. The function gregoriantojd (per the manual entry here) returns a value in days, not seconds. I like the date_diff conversion that Piotr gives the best.

2nd question: how do I convert the seconds and convert them to years (as an integer)?!

Well, if you were starting with a number of seconds (which you aren't) then your second formula would be mostly correct, but of course it wouldn't account for leap-years. So for anyone older than 4, or at least 8, it would be off for one or more days around their birthday. Usually on their birthday is a pretty important time to get their age correct.

David Winant
  • 832
  • 4
  • 8