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

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

帮助将不胜感激!

4

3 回答 3

3

考虑这一点的最简单方法是,如果您知道此人的出生日期,您只需确定他们的 18 岁生日是否已过。

  1. 询问用户他们的出生日期。以日、月和年的形式获取。
  2. 将 18 添加到年份。
  3. 将其转换为带有EncodeDate.
  4. 将其与今天的日期进行比较,可以通过调用找到Date

代码如下所示:

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');

看起来我刚刚在这里重新发明了轮子。总是一个坏主意。你可以打电话IncYearDateUtils完成这项工作,而不必担心闰日。

if IncYear(EncodeDate(dobYear, dobMonth, dobDay), 18) > Date then
  ShowMessage('Too young');
于 2013-10-14T14:09:09.677 回答
0

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

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

{============================================================}
于 2014-10-13T07:56:48.940 回答
0

我认为这更简单:

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

岁月之间

于 2019-10-30T23:22:03.277 回答