Calculate age based on date of birth
Here is some sample PHP code that calculates a person's age based on their date of birth:
<?php
function calculateAge($dob)
{
$today = new DateTime();
$diff = $today->diff(new DateTime($dob));
return $diff->y;
}
$dob = '2000-01-01';
$age = calculateAge($dob);
echo "Age is: $age";
This code creates a calculateAge
function that takes a date of birth (in the format 'YYYY-MM-DD') as a parameter. It then creates a new DateTime
object representing the current date, and calculates the difference between the current date and the date of birth using the diff
method. The difference is returned in a DateInterval
object, and we can access the number of years using the y
property. Finally, the age is printed to the screen.
Note that this code does not take into account the exact date of birth, only the year, month, and day. If you want to be more precise, you can use the diff
method's format
parameter to output the interval in a more detailed format.