Determining Person Age

by Feb 2, 2017

How do you calculate the age of a person, based on birthday? You can subtract the current time delivered by Get-Date from the birthday, but the result does not contain years:

#requires -Version 1.0

$birthday = Get-Date -Date '1978-12-09'
$today = Get-Date
$timedifference = $today - $birthday

$timedifference

Here is the result:

 
Days              : 13905
Hours             : 16
Minutes           : 34
Seconds           : 58
Milliseconds      : 575
Ticks             : 12014516985758198
TotalDays         : 13905.6909557387
TotalHours        : 333736.582937728
TotalMinutes      : 20024194.9762637
TotalSeconds      : 1201451698.57582
TotalMilliseconds : 1201451698575.82
 

To calculate the years, take the number of “ticks” (the smallest unit of time measurement), and convert it to a datetime, then take the year and subtract one:

#requires -Version 1.0
$birthdayString = '1978-12-09'
$birthday = Get-Date -Date $birthdayString
$today = Get-Date
$timedifference = $today - $birthday
$ticks = $timedifference.Ticks
$age = (New-Object DateTime -ArgumentList $ticks).Year -1
"Born on $birthdayString = $age Years old (at time of printing)"

And this is what the result would look like:

 
Born on 1978-12-09 = 38 Years old (at time of printing)
 

Twitter This Tip! ReTweet this Tip!