How to Calculate Age in PowerShell (DateTime and Birthday Logic Examples)
Learn how to calculate age from date of birth in PowerShell using DateTime, with a clean birthday check for completed years.
How to Calculate Age in PowerShell (DateTime and Birthday Logic Examples)
In PowerShell, age usually means the number of completed years. The reliable pattern is simple: subtract the birth year, then reduce by one if the birthday has not happened yet in the reference year.
Fast option: use an online age calculator
If you want a quick check, or you need the exact result in years, months, and days, verify the dates in a calculator first and then mirror the same rule in code.
Open the age calculator and enter the date of birth plus the reference date.
PowerShell example with DateTime
This helper returns completed years as of a given date.
function Get-AgeYears {
param(
[datetime]$DateOfBirth,
[datetime]$AsOf = (Get-Date)
)
$years = $AsOf.Year - $DateOfBirth.Year
$hadBirthday = ($AsOf.Month -gt $DateOfBirth.Month) -or
(($AsOf.Month -eq $DateOfBirth.Month) -and ($AsOf.Day -ge $DateOfBirth.Day))
if (-not $hadBirthday) { $years-- }
return $years
}
Get-AgeYears -DateOfBirth ([datetime]'1998-10-12')
Parsing from an ISO date string
If the input already looks like 1998-10-12, you can cast it directly before passing it to the helper.
$dob = [datetime]'1998-10-12'
$years = Get-AgeYears -DateOfBirth $dob
FAQ
Why not divide days by 365.25?
That can work as a rough estimate, but real age should follow birthdays. A direct birthday check avoids the usual off-by-one problems.
How do I calculate exact age in years, months, and days?
That is a separate problem because month lengths vary. It helps to validate your result with a dedicated calculator before using it in app logic.