Delphi通过TDateEdit组件计算人员年龄

-1 delphi datetime date-arithmetic

我有一个非常简单的形式有TDateEditTButtonTLabel组件。 在此处输入图片说明

如果给定的日期是某人的生日,那么获得该年龄的最佳方法是什么?有人将如何在Delphi中通过TDateEdit组件执行此操作,然后在标签中显示年龄?

组件中是否可能有内置功能或可以用来确定某人年龄的信息?我正在寻找最简单,最简单和最佳的方法。

Ian*_*oyd 7

这是一个计算某人年龄的函数。

它与RTL函数YearsBetween明显不同,它可以计算两个日期之间的年数。基本上与某人的年龄不同。

function GetAge(const BirthDate, CurrentDate: TDateTime): Integer;
var
    y1, m1, d1: Word; //born
    y2, m2, d2: Word; //today
begin
    Result := 0;

    if CurrentDate < BirthDate then
        Exit;

    DecodeDate(BirthDate, y1, m1, d1);
    DecodeDate(CurrentDate, y2, m2, d2);

    //Fudge someone born on the leap-day to Feb 28th of the same year
    //strictly for the purposes of this calculation
    if ( (m1=2) and (d1=29) )
            and
        ( not IsLeapYear(y2) ) then
    begin
        d1 := 28;
    end;

    Result := y2-y1; //rough count of years
    //Take away a year of the month/day is before their birth month/day
    if (m2 < m1) or
            ((m2=m1) and (d2<d1)) then
        Dec(Result);
end;
Run Code Online (Sandbox Code Playgroud)