Open In App

Program to Calculate Age in Years in PHP

Given the current date and birth date, find the present age. 

Below are approaches to calculating age based on a given birth date:

Using DateTime class

This approach uses the DateTime class to create DateTime objects for the birth date and current date. It then calculates the difference between the two dates using diff and extracts the number of years from the difference.

Example: This example uses the DateTime class to calculate age in years in PHP.

<?php
    $birth_date = '2001-04-12';
    $current_date = date('Y-m-d');
    $birth_date_obj = new DateTime($birth_date);
    $current_date_obj = new DateTime($current_date);
    $diff = $current_date_obj->diff($birth_date_obj);
    $age_years = $diff->y;
    echo "Age: $age_years years";

?>

Output
Age: 23 years

Using timestamps and division

In this approach, we will convert the birth date and current date to timestamps using strtotime and calculate the difference in seconds between the two timestamps. Then we calculate the age in years by dividing the difference by the number of seconds in a year. In this example, we are using timestamps and division to calculate the age in a year in PHP.

Example: This example uses tmiestamps and division to calculate age in years in PHP.

<?php
    $birth_date = '2004-06-18';
    $current_date = date('Y-m-d');
    $birth_timestamp = strtotime($birth_date);
    $current_timestamp = strtotime($current_date);
    $diff_seconds = $current_timestamp - $birth_timestamp;
    $age_years = $diff_seconds / (60 * 60 * 24 * 365.25);
    $age_years = round($age_years);
    echo "Age: $age_years years";

?>

Output
Age: 20 years
Article Tags :