PHP: Calculating Age from DOB in "dd/mm/yyyy" Format
Calculating the age of a person from their date of birth can be a challenging task, especially when dealing with large quantities of data. This question focuses on a specific challenge encountered with a previous method that utilized a while loop to increment the age until the current date was reached.
One alternative method suggested in the question involves using the strtotime() and floor() functions to calculate the difference between the current time and the date of birth. However, as noted, this method also faces limitations.
A Reliable Solution
A more reliable approach is to calculate the age based on the day and month of the date of birth and the current date. Here's a revised PHP function that addresses the issues encountered:
<?php function calculateAge($birthDate) { $birthDate = explode("/", $birthDate); $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") ? ((date("Y") - $birthDate[2]) - 1) : (date("Y") - $birthDate[2])); return $age; } $dob = "14/09/1986"; $age = calculateAge($dob); echo "Age: ".$age; ?>
Implementation Details
This approach provides a precise and efficient way to calculate the age of an individual, regardless of the number of DOBs being processed.
The above is the detailed content of How to Reliably Calculate Age from a DD/MM/YYYY Date of Birth in PHP?. For more information, please follow other related articles on the PHP Chinese website!