How to calculate age from a given birthdate in php
How to calculate age from a given birthdate in php?
Has anyone needed to get the user age based on the profile birthdate? Well you probably thought about it now. It is possible to this and its user friendly to let someone know how old they are. Of course some of you may not want to have the age shown, but that’s a different matter.
There are a few solutions you can use for this, below there are two solutions that we recommend.
This solution is not limited by the input date. You can pass any format you want (not a specific format needed, but needs to be a well known format for PHP).
1st solution (PHP >=5.3)
1 2 3 4 |
function birthday($birthday) { $diff = date_diff(date_create(), date_create($birthday)); return $diff->y; } |
The above solution will also support any date format that’s acceptable to PHP, not limited to YYYY-MM-DD.
Sample usage:
1 |
birthday("1989-03-30"); // This will echo 24 (31 Jan. 2014 date I tested this) |
2nd solution
1 2 3 4 5 |
$bday = new DateTime('30.01.1989'); $today = new DateTime('00:00:00'); // use this for the current date $diff = $today->diff($bday); printf('%d years', $diff->y-1, $diff->m, $diff->d); |
I will strongly recommend to use the first solution if you have the required version of PHP, because it is covering more ground and it is also their native solution, it should be better than any other one.
That’s it for now, will see you again in our next tutorial.