Article
· Feb 21, 2018 1m read

Calculate the age of a person

Hi all,

I've created a method to calculate the age of a person, or the age of a process, contract or other stuff as you want.

/// Calculate the age from date of birth and other date (by default shoud be today).
/// <b>dateOfBird</b> Date of birth in cache format. ie. $ZDH("1972-01-01",3)
/// <b>day</b> Date to calculate to. ie: $H
ClassMethod AgeAt(dateOfBirth, day) As %Integer{
    quit:dateOfBirth=""
    quit:day=""
    
    set yeardob=$SYSTEM.SQL.DATEPART("year",dateOfBirth)
    set yearday=$SYSTEM.SQL.DATEPART("year",day)
    
    set years=yearday-yeardob
    kill yeardob, yearday
    
    set monthdob=$SYSTEM.SQL.DATEPART("month",dateOfBirth)
    set monthday=$SYSTEM.SQL.DATEPART("month",day)
    if (monthday-monthdob)<0 set years=years-1
    if (monthdob-monthday)=0
    {
        if ($SYSTEM.SQL.DATEPART("day",day) - $SYSTEM.SQL.DATEPART("day",dateOfBirth)) < 0
        {
            set years=years-1
        }
    }
    
    kill monthdob, monthday
    quit years
}

I hope this method is useful for you

Best regards

[EDITED] Thanks @Marcus Magina for improve this method by a easy way.

Discussion (2)1
Log in or sign up to continue