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
}

 

Answers

you can use function DATEDIFF from SQL

write $system.SQL.DATEDIFF("yy", $zdh("01.01.1990",4), $h)

In this case $system.SQL.DATEDIFF is not suitable:

USER>w $system.SQL.DATEDIFF("yy"$zdh("30.12.1990",4), $zdh("01.01.1991",4))
1

USER>($ZD($zdh("01.01.1991",4),8)-$ZD($zdh("30.12.1990",4),8))\10000
0

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))
}

Comments

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