Blog
Calculate Age from Date of Birth in PHP
To calculate age from a date of birth in PHP, parse the birth date and reference date with DateTimeImmutable, reject invalid or reversed dates, and read the completed-year component from $birth->diff($asOf)->y. Use the interval’s total days property for day and week totals rather than dividing by 365.
This tutorial includes strict date validation, a selectable as-of date, leap-year examples, a browser-only live demo, and a downloadable PHP calculator. The date-only results show completed years, calendar days, weeks and remaining days, with clearly labelled nominal time-unit conversions.
Live demo: calculate age from date of birth
Choose a birth date and an as-of date, or use the fictional sample. The embedded demo runs in JavaScript and keeps the dates in this page. The ZIP contains the corresponding PHP implementation for server-side calculation.
Age from date of birth
Choose two calendar dates. This browser demo runs locally; the ZIP also includes the PHP calculator.
Choose a birth date and an as of date, then calculate.
Show nominal 24-hour conversions
These multiply calendar days by fixed units. They do not measure time since an actual birth instant.
Date-only calculation using UTC midnights. February 29 birthdays reach the next completed year on March 1 in a non-leap year under this convention. No dates are sent or stored by this demo.
JavaScript is needed for this browser preview. Use the downloadable PHP version for server-side calculation.
1. Parse dates strictly with DateTimeImmutable
Expect one explicit format, such as YYYY-MM-DD. PHP can normalize some invalid calendar values, so parsing alone is not sufficient validation. Check errors and warnings, then confirm that formatting the result gives the original value:
function swcParseDate(string $raw): DateTimeImmutable {
if(!preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/D',$raw) || (int)substr($raw,0,4)<1) throw new InvalidArgumentException('Use a valid YYYY-MM-DD date with a year from 0001 to 9999.');
$date=DateTimeImmutable::createFromFormat('!Y-m-d',$raw,new DateTimeZone('UTC'));
$errors=DateTimeImmutable::getLastErrors();
if($date===false || ($errors!==false && ($errors['warning_count']>0 || $errors['error_count']>0)) || $date->format('Y-m-d')!==$raw) throw new InvalidArgumentException('Choose a real calendar date.');
return $date;
}
The ! resets unspecified time fields, and the UTC timezone makes this date-only convention explicit. PHP’s createFromFormat reference documents parsing behavior, including overflow values. The getLastErrors reference describes diagnostics; a successful parse can return false for the diagnostics when there are no warnings or errors.
2. Reject a birth date after the reference date
$birth = swcParseDate($birthRaw);
$asOf = swcParseDate($asOfRaw);
if ($birth > $asOf) {
throw new InvalidArgumentException('Birth must not be after the as-of date.');
}
$interval = $birth->diff($asOf);
$completedYears = $interval->y;
$totalDays = (int) $interval->days;
The reference date can be today or a date chosen for a reproducible calculation. Do not silently turn a reversed date range into a positive age. Browser date controls help input, but the PHP endpoint must validate its own POST values too.
3. Use completed birthdays, not days divided by 365
A calendar year can contain 365 or 366 days. A completed-year calculation also depends on whether the birthday has occurred by the reference date. For a birth date of 2000-01-15:
| As of date | Completed years |
|---|---|
| 2025-01-14 | 24 |
| 2025-01-15 | 25 |
| 2025-01-16 | 25 |
PHP’s DateTimeInterface::diff reference explains calendar intervals and timezone effects. Here both endpoints represent UTC midnight for selected calendar dates. This avoids daylight-saving offsets when counting date-only days.
4. Calculate total days and weeks correctly
$days = (int) $interval->days;
$weeks = intdiv($days, 7);
$remainingDays = $days % 7;
$interval->d is the remaining day component of a calendar interval. It is not the total number of days. To express a total duration in weeks plus days, divide the total day count by seven and take the remainder from that same total.
For 2000-01-15 through 2025-01-15, this implementation returns 25 completed years, 9,132 calendar days, or 1,304 weeks and 4 days. Day counts exclude an extra inclusive-endpoint day: a date compared with itself has a difference of zero days.
February 29 birthdays and month-end dates
This calculator uses a stated convention: a February 29 birth date reaches the next completed year on March 1 in a non-leap year. For example, 2000-02-29 to 2023-02-28 gives 22 completed years; to 2023-03-01 gives 23. This is the software’s date convention, not a legal rule for age eligibility.
If your application needs years, months and remaining days, PHP also exposes $interval->y, $interval->m and $interval->d. Month lengths vary, so do not replace calendar month arithmetic with a fixed 30-day divisor. This demo focuses on completed years and total-day equivalents rather than inventing a fixed-length month.
Hours, minutes and seconds need a clear assumption
A date of birth does not specify an actual birth time or timezone. The optional conversions below multiply calendar days by fixed unit lengths:
$nominalHours = $days * 24;
$nominalMinutes = $days * 24 * 60;
$nominalSeconds = $days * 24 * 60 * 60;
These are nominal 24-hour conversions of the date-only difference, not an exact age in elapsed seconds. For an instant-based calculation, collect the required birth time and timezone and define the endpoint instant. The sample deliberately separates these two meanings.
Run the PHP calculator locally
- Extract the ZIP.
- Use a supported 64-bit PHP 8.x installation.
- Open a terminal in the extracted project folder and run the command below.
- Open
http://127.0.0.1:8080/php/index.php.
php -S 127.0.0.1:8080
The built-in server is for localhost development. The PHP page works without JavaScript and needs no database, Composer package or API key. Its form sends both dates to the local PHP application by POST. That sample does not store the dates; hosting logs and infrastructure policies are separate if you deploy it publicly.
php-age-calculator-demo/
├── index.html
├── style.css
├── age.js
├── script.js
├── README.md
└── php/
├── age.php
└── index.php
Open the root index.html for the browser-only version. The browser defaults its as-of date to the local calendar date; PHP defaults to today’s UTC date. These can differ near midnight, so enter the same explicit reference date when comparing results. WordPress post content runs the browser preview, not the downloadable PHP files.
Validation and implementation checklist
| Case | Expected behavior |
|---|---|
| Missing or malformed date | Show a validation message and no stale result. |
| February 30 or April 31 | Reject the impossible date rather than normalize it. |
| Birth after as-of date | Reject the reversed range. |
| Same birth and as-of date | Return zero years and zero days. |
| Birthday tomorrow, today or yesterday | Increment completed years only when the birthday is reached. |
| Leap-year boundaries | Apply actual Gregorian calendar dates and the stated February 29 convention. |
| Edited or restored fields | Hide previous results until recalculation. |
The PHP form escapes reflected values and rejects non-string POST fields before calculation. If you add a database, logging or age-restricted behavior, design those separately around your application’s data and date policies.
Frequently asked questions
What is the simplest PHP age calculation?
For already validated dates in a consistent timezone, use $birth->diff($reference)->y. Validate inputs and reject reversed ranges before applying it.
Why not divide seconds by 365 days?
That assumes every calendar year has the same length and can give the wrong completed age around birthdays and leap years.
What is the difference between diff days and d?
The days property gives the total day difference for an interval produced by diff. The d component is the remaining days after calendar years and months.
Does the public demo send my birth date to PHP?
No. The embedded calculator runs locally in the browser. The separate PHP form in the ZIP sends its inputs to the PHP application you run.
Does February 29 always become February 28?
No universal policy is assumed. This example uses March 1 in non-leap years; other application requirements may need a different explicit convention.
Can it calculate age at a future reference date?
Yes. The reference date is user-selected, provided the birth date is not after it. That is an age-on-date calculation rather than a claim about someone’s current age.
Try the examples and download the source
Start with the sample dates, then test birthday boundaries, leap days and a reversed date range. Use the ZIP to inspect and run the PHP version alongside the browser preview.