字面翻譯就是如下:
uses
..., DateUtils;
if (month > MonthOf(Date)) or ((day > DayOf(Date)) and (month > MonthOf(Date)) then
begin
age := YearOf(Date) - year - 1;
end else
begin
age := YearOf(Date) - year;
end;
但這不是最好的翻譯。如果沒有別的,如果代碼在當前日期更改的午夜運行,則重複調用Date()
會導致問題。下面會更安全:
uses
..., SysUtils;
var
wYear, wMonth, wDay: Word:
begin
...
DecodeDate(Date, wYear, wMonth, wDay);
if (month > wMonth) or ((day > wDay) and (month > wMonth) then
begin
age := wYear - year - 1;
end else
begin
age := wYear - year;
end;
...
end;
或者,看看在DateUtils.YearsBetween()
功能:
uses
..., SysUtils, DateUtils;
age := YearsBetween(Date, EncodeDate(year, month, day));
在功能看這裏將是一個良好的開端http://www.delphibasics.co.uk /ByFunction.asp?Main=DatesAndTimes –
查看[DecodeDate](http://docwiki.embarcadero.com/Libraries/XE2/de/System.SysUtils.DecodeDate)和[Now](http:// docs。 embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/SysUtils_Now.html) – bummi
例如,如果Month> MonthOf(Now)或(Day> DayOf(Now))和(Month> MonthOf(Now)),則Age:= YearOf(Now) - Year - 1 else Age:= YearOf(Now) - Year; ',但是這樣的代碼需要改進很多。 – TLama