Thursday, 9 August 2018

PHP: Calculating A Person’s Age From Their Date Of Birth.

A lot of web applications make the mistake of asking the user to manually enter his or her age. The problem with this approach is that the data becomes redundant if the user doesn’t take the time to update their profile information. i.e. You’re never quite sure how many birthdays the user has had since they first registered with your website.
The best approach is to ask the user to enter his or her date of birth. That way, you can actually calculate what their age is and there is no need for them to update it.
If you’re using PHP version 5.3.0 or above, then you can make use of the DateTime object:
In the code snippet above, you can see that calculating a person’s date of birth with the DateTime object is pretty simple and straight-forward. No need for overly-complex functions!
If you are using a PHP version that is lower than 5.3.0, then you will need to do something like this:
As you can see, you have to do a lot of the Math yourself.
If you’re looking for a function to use, you can try this:
Hopefully, you found this tutorial helpful!

0 comments:

Post a Comment