Question
· Dec 5, 2017

How to Subtract or Add dates

I am trying to age based on a given date and current date here is my code:


Property DOB As %Date
Method GetAge() As %Integer
{
   if (..DOB="")
    {
  set today=0 
    }
   else
  {
  set today=$ZDate($HOROLOG,2)-$ZDate(..DOB)
  }
  write "Today's==="_$ZDate($HOROLOG),!
  write today
  return today
}

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

See Sample.Person in "SAMPLES".

/// Person's age.<br>
/// This is a calculated field whose value is derived from <property>DOB</property>.
Property Age As %Integer CalculatedSqlComputeCode = { Set {Age}=##class(Sample.Person).CurrentAge({DOB})}, SqlComputedSqlComputeOnChange = DOB ];

/// This class method calculates a current age given a date of birth <var>date</var>.
ClassMethod CurrentAge(date As %Date ""As %Integer CodeMode = expression ]
{
$Select(date="":"",1:($ZD($H,8)-$ZD(date,8)\10000))
}

I won't embarrass myself by listing the MUMPS code from 1991 that does this on our application, but I will comment that you need to work out how many birthdays have gone by so it must compare month and day values once the basic year subtraction has been done. It gets quite complicated. (Might also like to look at whether you need more than just a "years old", and also need months or days for very low values.)

Mike