How to calculate age from a given birthdate in php

→ Are you a new visitor? Please visit the page guidance for new visitors ←

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)

The above solution will also support any date format that’s acceptable to PHP, not limited to YYYY-MM-DD.

Sample usage:

2nd solution

Warning! This solution will is not a exactly recommended to be used in production. It is just an example to show you that it is possible using DateTime class.

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.

Request an article ←