I love elegant, clean, code solutions, and this is one my favorites. We’ve all had the issue of how to compute a person’s age when you know their date of birth, and you have a date at which you need to know what their age will be.
For example, I might know DOB and want to compute someone’s age at the next billing date.
This is it… one line of PHP brilliance 😉
$age = date_diff(date_create($_SESSION["current_subscriber_birthdate"]), date_create($_SESSION["next_bill_date"]))->y;
I’m not sure what version of PHP is required to support this, but I’m using 5.3. Strictly speaking this code is computing the number of complete years between any two dates. Which is usually what we want when determining someone’s age for insurance or healthcare applications and so on.
We create a couple of date variables from regular date strings using the date_create( ) function. In my example my two dates involved are in session variables.
Then use date_diff( date1, date2) to get the resulting difference between the two dates, and finally… use object notation to extract just the year part from the result, and return just that to the $age variable.
Le voila! you have age in years without going through any convoluted year math, month additions, or other compensations for leap years etc!