Calculate Age from Date of Birth in PHP: Step-by-Step Guide

To calculate age from a date of birth in PHP, you can use the DateTime class along with some basic arithmetic. Here’s a step-by-step guide on how to achieve this:

Step 1: Get the Date of Birth (DOB) from the user or any other data source.

$date_of_birth = '1990-06-15';

Step 2: Create a DateTime object for the date of birth.

$DOB = new DateTime($date_of_birth);

Step 3: Get the current date as a DateTime object.

$current_date = new DateTime();

Step 4: Calculate the difference between the current date and the date of birth.

$age_interval = $current_date->diff($DOB);

Step 5: Extract the calculated age from the $age_interval object.

$age = $age_interval->y;

The variable $age now contains the calculated age based on the date of birth. You can use it for further processing or display.

Here’s the complete code in one block:

<?php
$date_of_birth = '1990-06-15';
$DOB = new DateTime($date_of_birth);
$current_date = new DateTime();
$age_interval = $current_date->diff($DOB);
$age = $age_interval->y;

echo "Age: " . $age . " years";
?>

The output will be something like:

Age: 31 years

In this example, we use the DateTime class to handle dates and calculate the difference (interval) between the current date and the date of birth. The diff() method of DateTime calculates the difference and returns a DateInterval object, from which we extract the number of years using the y property.

This method accounts for leap years and handles the edge cases correctly, ensuring accurate age calculation.