计算德尔福的年龄

时间:2013-10-14 14:05:37

标签: delphi

iAge := 2013 - StrToInt(sJ) ;
if iAge< 18
then
begin
bDatum := False ;
ShowMessage('You must be older than 18!') ;
Exit ;
end; //IF

如果你使用它,它只需要用户输入的当前年份和年份,并测试他是否是18岁,我正在寻找一种方法来计算使用月份和日期的用户的年龄同样但它无济于事,所以我希望得到Stackoverflow的帮助。

非常感谢帮助!

3 个答案:

答案 0 :(得分:3)

最简单的思考方式是,如果你知道这个人出生的日期,你只需要弄清楚他们的18岁生日是否过去了。

  1. 询问用户的出生日期。以日,月和年的形式获得。
  2. 年内增加18个。
  3. 将其转换为EncodeDate的日期。
  4. 将其与今天的日期进行比较,可以通过致电Date找到。
  5. 代码如下所示:

    if EncodeDate(dobYear + 18, dobMonth, dobDay) > Date then
      ShowMessage('Too young');
    

    现在,这几乎可以奏效,但是如果这个人出生在闰日,即2月29日那么它就会失败。你需要添加一个特殊的案例来处理它。例如,粗略的方法是这样的:

    if (dobMonth=2) and (dobDay=29) then
      dobDay := 28;
    if EncodeDate(dobYear + 18, dobMonth, dobDay) > Date then
      ShowMessage('Too young');
    

    看起来我刚刚在这里重新发明了轮子。总是一个坏主意。您可以从IncYear拨打DateUtils来完成此操作,而不必担心闰日。

    if IncYear(EncodeDate(dobYear, dobMonth, dobDay), 18) > Date then
      ShowMessage('Too young');
    

答案 1 :(得分:0)

Delphi将日期存储为实数 - 您必须使用扩展类型

function Age(TheDate: TDate): integer;

var

  I: Extended;                                   // Extended is a special type of real variable

begin

  I := Now() - TheDate;                     // Now() is todays date in TDate format

                                                          //  The type conflict is apparently ignored



  Result := round(I/365.25);

  If Result > 110 then Result := 0;    // this copes with a missing date string



end; // Start date in Delphi is 30/12/1899

{============================================================}

答案 2 :(得分:0)

我认为这很简单:

isUnder18 := YearsBetween(DOB, Now()) < 18;

YearsBetween