unit ScreenAgeCalculation; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls; type TFormCalcAge = class(TForm) DateTimePickerBirthDate: TDateTimePicker; DateTimePickerTestDate: TDateTimePicker; LabelAge: TLabel; Label1: TLabel; Label2: TLabel; procedure DateTimePickerChange(Sender: TObject); procedure FormCreate(Sender: TObject); private public { Public declarations } end; var FormCalcAge: TFormCalcAge; implementation {$R *.DFM} USES CommCtrl; // To set format of TDateTimePickers // Age[years] could be calculated by dividing a difference of two TDates by // about 365.25, but this will be wrong by a day or so from time to time // (especially since 1900 and 2100 are not leap years, but 2000 is). "Simple" // comparision of the TestDate against the BirthDate does yield the desired // "common sense" age. FUNCTION CalculateAge (CONST BirthDate: TDate; CONST TestDate: TDate): INTEGER; VAR DayBirth, DayTest : WORD; MonthBirth, MonthTest: WORD; YearBirth, YearTest : WORD; BEGIN IF TestDate > BirthDate THEN BEGIN DecodeDate(BirthDate, YearBirth, MonthBirth, DayBirth); DecodeDate(TestDate, YearTest, MonthTest, DayTest); // Code algorithm this way so anyone can understand what is going on here. IF MonthTest > MonthBirth // Any month past BirthDate THEN RESULT := YearTest - YearBirth ELSE BEGIN IF MonthTest < MonthBirth // Any month before BirthDate THEN RESULT := YearTest - YearBirth - 1 ELSE BEGIN IF DayTest >= DayBirth // On or after BirthDate THEN RESULT := YearTest - YearBirth ELSE RESULT := YearTest - YearBirth - 1 END END END ELSE RESULT := 0 // Ignore TestDate before BirthDate END; procedure TFormCalcAge.DateTimePickerChange(Sender: TObject); VAR Years: INTEGER; begin Years := CalculateAge(DateTimePickerBirthDate.Date, DateTimePickerTestDate.Date); LabelAge.Caption := 'Age: ' + IntToStr(Years) + ' years'; end; procedure TFormCalcAge.FormCreate(Sender: TObject); begin // This does nothing to/for a TDateTimePicker SysUtils.ShortDateFormat := 'M/dd/yyyy'; // Show 4-digit years DateTime_SetFormat(DateTimePickerBirthDate.Handle, pChar('M/d/yyy')); DateTime_SetFormat(DateTimePickerTestDate.Handle, pChar('M/d/yyy')); end; end.