Class and Recorder Helper example
Example code : How old are you?
{YearsBetween function}
function SpanOfNowAndThen(const ANow, AThen: Float): Float;
begin
if ANow < AThen then
Result := AThen - ANow
else
Result := ANow - AThen;
end;
function DaySpan(const ANow, AThen: Float): Float;
Result := SpanOfNowAndThen(ANow, AThen);
function YearSpan(const ANow, AThen: Float): Float;
Result := DaySpan(ANow, AThen) / 365.25;
function YearsBetween(const ANow, AThen: Float): Integer;
Result := Trunc(YearSpan(ANow, AThen));
{ TPessoa class }
type
TPessoa = class
private
FDataNasc: TDateTime;
public
property DataNasc: TDateTime read FDataNasc write FDataNasc;
TPessoaHelper = class helper for TPessoa
function GetIdade: integer;
property Idade: integer read GetIdade;
TIntHelper = record helper for integer
function ToStr(): String;
{ TPessoaHelper }
function TPessoaHelper.GetIdade: integer;
Result := YearsBetween(Self.DataNasc, Now);
{ TIntHelper }
function TIntHelper.ToStr: String;
Result := IntToStr(Self);
procedure TForm1.W3Button5Click(Sender: TObject);
var
oPessoa: TPessoa;
oPessoa := TPessoa.Create;
try
oPessoa.DataNasc := EncodeDate(1986, 11, 26); // StrToDate('1986-26-11');
Edit1.Text := (oPessoa.Idade).ToStr;
finally
oPessoa.Free;
Today: 08/17/2014
BirthDate: 1986/26/11
Today - BirthDate = 27
Note that we are using ToStr function instead of IntToStr.