Home > Blockchain >  How do I calculate the age of the user in Powershell
How do I calculate the age of the user in Powershell

Time:03-18

I'm trying to write a function in Powershell where I calculate the age of the user based on the birthdate. So it should probably be currentdate - birthdate and put the difference in years. I'm getting stuck however, on the formating of these dates because the user has to input their birthdate.

Function getAge ($birthDate)
{
    $currentDate = Get-Date
    $age = $currentDate - $birtDate
    Write-Host "Your age is $age"
}
getAge 24-01-1991

CodePudding user response:

Your function is almost there, except for the fact that it creates and returns a TimeSpan object with the difference between the current and the given date.

Try

function Get-Age {
    param (
        [Parameter(Mandatory = $true)]
        [datetime]$birthDate
    ) 
    $currentDate = Get-Date
    $age = $currentDate - $birthDate

    # use the ticks property from the resulting TimeSpan object to 
    # create a new datetime object. From that, take the Year and subtract 1
    ([datetime]::new($age.Ticks)).Year - 1
}

# make sure the BirthDate parameter is a valid DateTime object
Get-Age ([datetime]::ParseExact('24-01-1991', 'dd-MM-yyyy', $null))

CodePudding user response:

First you need to convert the input parameter $birthDate, currently a string, to a DateTime object, for that you can use the ParseExact(..) method. Then you need to decide which type of date format your function will accept, I have added a ValidatePattern attribute to the function so that currently only accepts the pattern shown in your question, this however can be updated so that the function takes more than one format (ParseExact(..) can also parse multiple formats). Lastly, you're correct with Current Date - Birth Date, this will get us a TimeSpan object which has a .Days property, we can use the value of the property and divide it by the number of days in a year to obtain the user's age.

function getAge {
[cmdletbinding()]
param(
    [ValidatePattern('^(\d{2}-){2}\d{4}$')]
    [string]$birthDate
)

    $parsedDate = [datetime]::ParseExact(
        $birthDate,
        'dd-MM-yyyy',
        [cultureinfo]::InvariantCulture
    )

    [int] $age = ([datetime]::Now - $parsedDate).Days / 365
    Write-Host "Your age is $age"
}

getAge 24-01-1991
  • Related