Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Calculate Yrs, Mth, Dys from BDay

0 views
Skip to first unread message

David & Sherri Sovinski

unread,
Apr 28, 1998, 3:00:00 AM4/28/98
to

I need to calculate the exact number of Years, Months and Days from Now
to a persons Birthday.
Example: 4/28/98(Now) - 4/4/97(Birthday) should show me '1 Year 0
Months 24 Days'

DecodeDate calculates such that everything is calculated 1 Yr 1 Mo 1 Day
off when subtracting Now - BDay. So DecodeDate(Now-BDay, Yr, Mo, Day)
gives incorrect results. Could someone point me in the right direction?

Jorgen

unread,
Apr 30, 1998, 3:00:00 AM4/30/98
to David & Sherri Sovinski

Hi,
Enclosed is a method for calculating age in years, months or days. But I
think you can figure out how to put this together so your calculation is
correct.

{ I've set the DateSeparator to '-' by code. }
function CalculateAge(const dtBirthday: TDateTime): String;
var
dtToday: TDateTime;
nDays, nMonths, nYears: Integer;
yy, mmBd, ddBd, mmTd, ddTd: Word;
begin
dtToday := Date;
{ Calculate days between today and the birth date }
nDays := Trunc(dtToday - dtBirthday);

{ Calculate months between the two dates }
DecodeDate(dtBirthday, yy, mmBd, ddBd); { fetch date parts for birth
date }
DecodeDate(dtToday, yy, mmTd, ddTd); { fetch date parts for today }
if (ddTd < ddBd) then
Dec(mmTd);
if (mmTd < mmBd) then
Inc(mmTd, 12);
nMonths := mmTd - mmBd;

{ Calculate years between the two dates. If birth date hasn't passed
yet - remove one year }
nYears := StrToInt(FormatDateTime('yyyy', dtToday)) -
StrToInt(FormatDateTime('yyyy', dtBirthday));
if (FormatDateTime('mm-dd', dtToday) < FormatDateTime('mm-dd',
dtBirthday)) then
Dec(nYears);

{ Check result to return correct value }
if (nYears > 0) then
Result := Format('%d years', [nYears])
else if (nMonths > 0) then
Result := Format('%d months', [nMonths])
else { if (nDays > 0) then }
Result := Format('%d days', [nDays]);
end;

0 new messages