Skip to content

Instantly share code, notes, and snippets.

@johnmorris
Last active September 7, 2016 11:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save johnmorris/7851237 to your computer and use it in GitHub Desktop.
Save johnmorris/7851237 to your computer and use it in GitHub Desktop.
This PHP function accepts a birthday as a parameter and will return the age based on that birthday. Handy for social sites/applications.
<?php
// PHP 5.3-
function birthday($birthday){
$age = strtotime($birthday);
if($age === false){
return false;
}
list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age));
$now = strtotime("now");
list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now));
$age = $y2 - $y1;
if((int)($m2.$d2) < (int)($m1.$d1))
$age -= 1;
return $age;
}
echo birthday('1981-05-18');
// PHP 5.3+
function birthday($birthday) {
$age = date_create($birthday)->diff(date_create('today'))->y;
return $age;
}
echo birthday('1981-05-18');
@kisuka
Copy link

kisuka commented Dec 13, 2013

If php >= 5.3 you can reduce this to just 1 line by using:

echo date_create("1981-05-18")->diff(date_create("today"))->y;

@johnmorris
Copy link
Author

@kisuka Gist updated. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment