Found this cool snippet with returns how old is somebody from a given birthday.
function birthday($birthday){
list($year,$month,$day) = 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--;
return $year_diff;
}
Code language: PHP (php)
Please note there is a lot of variatons and I'm sure it could be done better.
Sheffield Website Design
Would this not be a lot easier? :
<?php $year = date('Y'); $dateofbirth = "1988"; $age = $year – $dateofbirth; print $age; ?>
twitter: @mgpwr
quicoto
Well the function I pasted also takes care about the month and day.
In your function being the 01-01-2011 or 31-12-2011 will return the same age. Wich is wrong, isn’t it? 😛
Thanks por posting.
Regards
Sumair
$year = date('Y'); $dateofbirth = $_POST["txtage"]; $age = $year - $dateofbirth;
i used this with a little change in ur code, to get value from user, & it worked,
thanks bro.
Rick
Way to go, glad it worked 😉
Sheffield Website Design
The title is: ‘How to Calculate Age with PHP’ and my age is 23, my d.o.b is 1988 – so that code for me outputs 23. It is off by the months you are right 🙂
In your example how do you pass a d.o.b into it? and print the results?
quicoto
You just need to call the function with the year-month-day 😉
<?php echo birthday("1988-11-20"); ?>
SF
You should only care about $day_diff if $month_diff is 0 (same month), or you’ll end up substracting from $year_diff even if only $day_diff is below 0.
if ( ( $day_diff < 0 && $month_diff == 0 ) || $month_diff < 0)
sujeet jaiswara
very nice notes for age calculation!!!