How to Calculate Age in PHP (DateTime and DateInterval Examples)
Learn how to calculate age from date of birth in PHP using DateTime and diff(). Includes full years, age as of a specific date, and common edge cases.
How to Calculate Age in PHP (DateTime and DateInterval Examples)
If you need to calculate age in PHP, the main thing to define is what age means. In most apps, you want years completed - not just the difference between two years.
1) Simple PHP example with DateTime
This is the standard way to calculate full age in years from a date of birth.
<?php
$dob = new DateTime('2000-10-05');
$today = new DateTime('today');
$age = $dob->diff($today)->y;
echo $age;
2) Age as of a specific date
Sometimes you need age on a past or future reference date, for example for reports or eligibility checks.
<?php
$dob = new DateTime('2000-10-05');
$asOf = new DateTime('2026-03-16');
$age = $dob->diff($asOf)->y;
echo $age;
3) Years, months, and days
If you need a more exact breakdown, PHP gives you that too.
<?php
$dob = new DateTime('2000-10-05');
$today = new DateTime('today');
$diff = $dob->diff($today);
echo $diff->y . ' years, ' . $diff->m . ' months, ' . $diff->d . ' days';
Common pitfalls
- Using only year subtraction:
date('Y') - birthYearis wrong before the birthday. - Time zones: for DOB checks, use calendar dates consistently.
- Future DOB values: validate input before calculating age.
Quick check without code
If you just want to verify one result quickly, use the online tool: Calculate Age Online.
Related guides
- How to Calculate Age (complete guide)
- How to Calculate Age in JavaScript
- How to Calculate Age in Python
FAQ
What does diff()->y return in PHP?
It returns the number of full years between two dates, which is usually the correct definition of age.
Can PHP calculate age in months and days too?
Yes. The DateInterval object returned by diff() includes years, months, and days.