Link to home
Start Free TrialLog in
Avatar of jorged
jorged

asked on

Age calculation

Hi,
I have a method that calculates a person's current age in years (which I now have rewritten). Now I'd like to calculate the age in years, months and days as well.
On the web I found a Javascript method that did this, but I found that it didn't calculate correctly every time.
The code looks like this after I've ported it to Delphi:

procedure CalculateAge(var nYears, nMonths, nDays: Integer; const dtBirthday, dtToday: TDateTime);
var
  yyBd, mmBd, ddBd, yyTd, mmTd, ddTd: Word;
  nY, nM, nD: Integer;
begin
  DecodeDate(dtToday, yyTd, mmTd, ddTd);
  DecodeDate(dtBirthday, yyBd, mmBd, ddBd);

  nY := yyTd - yyBd;

  if (mmTd >= mmBd) then
    nM := mmTd - mmBd
  else
    begin
      Dec(nY);
      nM := 12 + mmTd - mmBd;
    end;

  if (ddTd >= ddBd) then
    nD := ddTd - ddBd
  else
    begin
      Dec(nM);
      nD := 31 + ddTd - ddBd;

      if (nM < 0) then
        begin
          nM := 11;
          Dec(nY);
        end;
    end;
  nYears := nY;
  nMonths := nM;
  nDays := nD;
end;

Could someone please tell me what is wrong with the code snipet above? Does anyone have a better solution? I'm completely stuck. I've tried almost everything.

Hope someone could help me...

-Jorgen
ASKER CERTIFIED SOLUTION
Avatar of stalefish
stalefish

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jorged
jorged

ASKER

Thank you,
I ported your code to Delphi and it works fine, but the code I've written myself while you wrote me this code, looks like it's a similar solution.

I also seem to have posted this question on the wrong forum, so this won't happen again. Sorry.

-Jorgen